簡體   English   中英

如何在 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!)

}

您可以使用上述方法將任何類型的日期從一種格式轉換為另一種格式。

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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM