1

I see people asking how to convert an ISO 8601 string to NSDate in Swift, but I need the exact opposite.

I understand how to get the epoch using 'timeIntervalSince1970' (Get Unix Epoch Time in Swift) which returns something like '1427058740.08374', but how do I convert that to ISO 8601?

Desired string: 2015-03-22T20:51:41+00:00

Community
  • 1
  • 1
Joe Isaacson
  • 4,012
  • 6
  • 30
  • 40
  • Did you have a look at NSDateFormatter, the ["Data Formatting Guide"](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html) and http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns ? – Martin R Mar 22 '15 at 21:32

3 Answers3

2
extension NSDate {
    var formattedISO8601: String {
        let formatter = NSDateFormatter()
        formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
        formatter.dateFormat = "yyyy-MM-dd'T'hh:mm:SSxxxxx"   //+00:00
        return formatter.stringFromDate(self)
    }
}

NSDate(timeIntervalSince1970: 1427058740.08374).formattedISO8601   // "2015-03-22T09:12:08+00:00"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
1

Swift 5

If you're targeting iOS 11.0+ / macOS 10.13+, you simply use ISO8601DateFormatter with the withInternetDateTime option, like so:

let unixTime = 1583358247

let date = Date(timeIntervalSince1970: TimeInterval(unixTime))
let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.formatOptions = [.withInternetDateTime]
let string = iso8601DateFormatter.string(from: date)

// string looks like "2020-03-04T21:44:07Z"
jrc
  • 20,354
  • 10
  • 69
  • 64
0

@LeoDabus's wonderful answer in Swift 4:

extension NSDate {
    var formattedISO8601: String {
        let formatter = DateFormatter()
        formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone!
        formatter.dateFormat = "yyyy-MM-dd'T'hh:mm:SSxxxxx"   //+00:00
        return formatter.string(from: self as Date)
    }
}

And to use it:

NSDate(timeIntervalSince1970: 1427058740.08374).formattedISO8601   // "2015-03-22T09:12:08+00:00"
agrippa
  • 819
  • 10
  • 8