0

How can I convert Sep 15, 2015, 20:49:00 to 2015-09-15T20:49:00 using Swift? I'm fetching a date object from Parse but need to convert it to a different format.

EDIT AFTER BEING MARKED DUPLICATE:

I'm using this :

let time = "Sat Sep 19 2015 19:03:47 GMT+0000 (UTC)"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
let date = dateFormatter.dateFromString(listenTime)

...and getting nil. So, what am I doing wrong?

slider
  • 2,736
  • 4
  • 33
  • 69
  • try like this: .dateFormat = "EEE' 'LLL' 'dd' 'yyyy' 'HH:mm:ss' GMT+0000 (UTC)'" You will need to specify also the calendar NSCalendarIdentifierISO8601, the timeZone "GMT" and the locale "en_US_POSIX" – Leo Dabus Sep 22 '15 at 01:11
  • Can you please post an answer? I'm getting the wrong hour. Must be a time zone issue. – slider Sep 22 '15 at 01:24
  • You are inputing UTC the hour it is probably your local time corresponding to the UTC time inputed – Leo Dabus Sep 22 '15 at 01:26
  • Ok so I don't want to change the time, just the format. How do I keep the time consistent? – slider Sep 22 '15 at 01:26
  • Just make sure the input is always GMT (UTC) – Leo Dabus Sep 22 '15 at 01:27
  • I'm doing `let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEE' 'LLL' 'dd' 'yyyy' 'HH:mm:ss' GMT+0000 (UTC)'" let date = dateFormatter.dateFromString(time)` and getting the wrong hour. I don't want to change the hour. – slider Sep 22 '15 at 01:28
  • http://stackoverflow.com/a/32706994/2303865 – Leo Dabus Sep 22 '15 at 01:30
  • Reopened because the selected duplicate was not at all a duplicate. – rmaddy Sep 22 '15 at 04:08
  • @dperk To convert a date string from one format to another you need two formats. One that matches the original string so you can convert the original string to an NSDate, and the second format to covert the NSDate to the new format. – rmaddy Sep 22 '15 at 04:09

1 Answers1

1
let time = "Sat Sep 19 2015 19:03:47 GMT+0000 (UTC)"
let df = NSDateFormatter()
df.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
df.locale = NSLocale(localeIdentifier: "en_US_POSIX")
df.timeZone = NSTimeZone(abbreviation: "GMT")
df.dateFormat = "EEE LLL dd yyyy HH:mm:ss' GMT+0000 (UTC)'"
if let date = df.dateFromString(time) {
    df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    let stringFromDate = df.stringFromDate(date)   // "2015-09-19T19:03:47"
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571