如何将 Swift 中的日期格式转换为另一种日期格式?

How can I convert a date format to another date format in Swift?

我目前有一个代码:

let now = NSDate()
let result: NSDate
result = Cal.iso8601.dateByAddingUnit(.Year, value: -5, toDate: now, options: [])!
return Cal.iso8601.startOfDayForDate(result)

以以下格式生成日期:

2016-09-15 22:00:00 +0000

我想将其转换为这种日期格式:

2016-09-16T13:49:23.221Z

如何在 Swift 中完成?

DateFormatter 需要大量资源,因此请使用此扩展,以便您只创建一个格式化程序实例。

struct Formatter {
    static let instance = NSDateFormatter(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
}
extension NSDateFormatter {
    convenience init(dateFormat: String) {
        self.init()
        self.dateFormat = dateFormat
    }
}

然后调用它:

// dateTime = the date that you want to format
let date = Formatter.instance.dateFromString(dateTime)
class func convertDateFormatFromOneFormatToOther(date: String,currentFormat: String,reqFormat : String) -> String
{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = currentFormat
    let date = dateFormatter.date(from: date)
    dateFormatter.dateFormat = reqFormat
    return  dateFormatter.string(from: date!)

}

you can use the above method to convert any type of date from one format to another format.

Usage: convertDateFormatFromOneFormatToOther(date: "04/03/2021 05:42:19 PM",currentFormat: "dd/MM/yyyy HH:mm:ss a",reqFormat : "dd MMM yyyy HH:mm:ss a")