From String to NSDate in Swift

旧时模样 提交于 2019-11-26 12:47:46

问题


I\'ve got a string containing a date in this format: Thu, 04 Sep 2014 10:50:12 +0000

Do you know how can I convert it to: 04-09-2014 (dd-MM-yyyy)

of course, using Swift


回答1:


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



回答2:


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.




回答3:


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/



来源:https://stackoverflow.com/questions/25686284/from-string-to-nsdate-in-swift

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