Search code examples
swiftnsdatedecoding

How to get system time in formatted style swift?


I have such time which I have to send to the server:

2019-03-06T14:49:55+01:00

I thought that I can do it in such way:

NSDate(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970))

but I got such time:

2021-01-24 15:42:31 +0000

I thought that I have to user decoding pattern, so used such way:

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss+z"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
        
let time = NSDate(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970))

if let date = dateFormatterGet.date(from: time.description) {
   print(dateFormatterPrint.string(from: date))
} else {
   print("There was an error decoding the string")
}

but its output was:

There was an error decoding the string

what means that I can't decode this time in such way. What I did wrong?


Solution

  • You are creating a string from a date from a time interval from a date, three of the conversions are waste.

    The conversion failed because time.description doesn't match the format yyyy-MM-dd HH:mm:ss+z

    To get an ISO8601 string with time zone the date format is yyyy-MM-dd'T'HH:mm:ssZ and you have to specify a fixed locale

    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let isoString = formatter.string(from: Date())
    

    There is a shorter way as suggested by Rob in the comments

    let formatter = ISO8601DateFormatter()
    formatter.timeZone = .current
    let isoString = formatter.string(from: Date())