在 Swift 中将日期转换为 "dd.MM.yyyy" 格式

Convert date to "dd.MM.yyyy" format in Swift

我使用 API,其中一个参数的类型为日期,格式为“dd.MM.yyyy”。

我无法转换它。我为日期创建了一个扩展,我试图以这种方式实现它:

extension Date {

  var shortDate: Date {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd.MM.yyyy"
    let strDate = formatter.string(from: self)
    let modifiedDate = formatter.date(from: strDate)
    return modifiedDate!
  }
}

我这样称呼它:

let day = Date().shortDate

不幸的是,它不起作用,看起来像这样:

2017-06-18 21:00:00 +0000

我该如何解决?

据我了解,您需要与 API 通信,它以 "dd.MM.yyyy” 格式表示日期。以下是您需要实现的简单功能:

class MyAPIFunctions
{
    static let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd.MM.yyyy"

        // make sure the following are the same as that used in the API
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.locale = Locale.current

        return formatter
    }()

    class func shortString(fromDate date: Date) -> String {
        return formatter.string(from: date)
    }

    class func date(fromShortString string: String) -> Date? {
        return formatter.date(from: string)
    }
}

我已将 formatter 声明为一个单独的常量,以节省每次调用时重新初始化的开销。 添加这些功能后,您可以将日期发送到 API,如下所示:

let today = Date()
let todayString = MyAPIFunctions.shortString(fromDate: today)
// send todayString to API

要将 API 中的字符串转换为 Date 对象,

let apiString = "17.07.2017"
guard let apiDate = MyAPIFunctions.date(fromShortString: apiString) else {
    // deal with formatting error here
    return
}
// work with apiDate object
 let date = Date.init()
        let formatter = DateFormatter()
        formatter.dateFormat = "dd-MM-yyyy"

        formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale!
        let strdate1 = formatter.string(from: date as Date)

        print(strdate1)