MMM dd, yyyy hh:mm:ss a 的正确 date.format 是多少?以及如何转换为 dd-mm-yyyy HH:ii

What is the correct date.format for MMM dd, yyyy hh:mm:ss a? and how convert to dd-mm-yyyy HH:ii

我想将其转换为:2017 年 12 月 31 日 8:00:00 PMdd-mm-yyyy HH:ii 格式 Swift 4.

到目前为止,这是我的代码:

let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMM dd, yyyy hh:mm:ss a"//this your string date format

    if let translatedDate = dateFormatter.date(from: datetime) {
        dateFormatter.dateFormat = "dd-MM-yyyy HH:ii"
        return dateFormatter.string(from: translatedDate)
    }

代码从不进入 if 语句。我想我的日期格式不正确。

一个 DateFormatter 在日期和它们的文本表示之间转换。

您可以找到更多 Locale 标识符 here

  • 首先,将您的日期转换为当地时区。使用 Locale class
  • 在您可以将日期转换为特定格式后。

并试试这个代码。

let dateStr = "Wed, 26 Jul 2017 18:10:02 +0530"
if let date = Date(fromString: dateStr, format: "MMM dd, yyyy hh:mm:ss a") {
        debugPrint(date.toString(format: "dd-MM-yyyy HH:ii"))
}

日期扩展是...

extension Date {

    // Initializes Date from string and format
    public init?(fromString string: String, format: String, identifier: String = Locale.current.identifier) {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        formatter.locale = Locale(identifier: identifier)
        if let date = formatter.date(from: string) {
            self = date
        } else {
            return nil
        }
    }

    // Converts Date to String, with format
    public func toString(format: String, identifier: String = Locale.current.identifier) -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: identifier)
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

字符串扩展是...

extension String {
    // Converts String to formated date string, with inputFormat and outputFormat
    public func toDate(form inputFormat: String, to outputFormat: String, identifier: String = Locale.current.identifier) -> String? {
        return Date(fromString: self, format: inputFormat, identifier: identifier)?.toString(format: outputFormat, identifier: identifier)
    }

    // Converts String to Date, with format
    func toDate(format: String, identifier: String = Locale.current.identifier) -> Date? {
        return Date(fromString: self, format: format, identifier: identifier)
    }
}