From String to NSDate in Swift

ぃ、小莉子 提交于 2019-11-27 09:21:26
csch

If the above doesn't work, this should do the trick:

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "US_en")
formatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z"
let date = formatter.date(from: "Thu, 04 Sep 2014 10:50:12 +0000")

I know the answer to this question has already been accepted but the shown method in that answer doesn't exactly output the date in the format of dd-MM-yyyy. So I'm gonna post this anyway so someone might find it useful.

One of the cool features of Swift is extensions. So I'm gonna create this as an extention so that it's reusable.

Create a extension for NSDate and put this code in there.

import Foundation

extension NSDate {

    convenience init(dateString: String) {
        let dateStringFormatter = NSDateFormatter()
        dateStringFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z"
        dateStringFormatter.timeZone = NSTimeZone(name: "GMT")
        let date = dateStringFormatter.dateFromString(dateString)

        self.init(timeInterval:0, sinceDate:date!)
    }

    func getDatePart() -> String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "dd-MM-yyyy"
        formatter.timeZone = NSTimeZone(name: "GMT")

        return formatter.stringFromDate(self)
    }
}

And this is how you use it.

NSDate(dateString: "Thu, 04 Sep 2014 10:50:12 +0000").getDatePart()

Output: 04-09-2014

You can change the formats in both functions to accept and output dates in various formats.

Try something like this:

let mydateFormatter = NSDateFormatter()
mydateFormatter.dateFormat = "EEE, MMM d, YYYY hh:mm:ss.SSSSxxx"
let date = mydateFormatter.dateFromString(yourdatestring)

Check out for the current date format if its not working: http://userguide.icu-project.org/formatparse/datetime/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!