From String to NSDate in Swift

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


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

Solution 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.

Solution 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/