0

I'm formatting a date string to date object using below code. But for some date strings it works and for some it returns nil.

Format = "yyyy-MM-dd'T'HH:mm:ss.sssZ"

"2019-04-02T09:47:24.055Z" Works

"2019-03-27T22:31:17.140Z" Doesn't work

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ"


let date = dateFormatter.date(from: "2019-03-27T22:31:17.140Z")
hashB
  • 113
  • 1
  • 12
  • 1
    Look at your date format. The format specifier for seconds and fractional seconds cannot be the same – vadian Apr 03 '19 at 09:47
  • 1
    As per @vadian suggestion you need to change your formate from `yyyy-MM-dd'T'HH:mm:ss.sssZ` to `yyyy-MM-dd'T'HH:mm:ss.SSSZ` – Chirag Shah Apr 03 '19 at 09:53

2 Answers2

6

Your format is wrong. It should be: "yyyy-MM-dd'T'HH:mm:ss.SSSZ" Have a look at date time format here: https://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns

Vuong Cuong
  • 192
  • 9
2
let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"


        let date = dateFormatter.date(from: "2019-04-02T09:47:24.055Z")
        let date1 = dateFormatter.date(from: "2019-03-27T22:31:17.140Z")
        print(">>>>>!!", date, date1)

Optional(2019-04-02 09:47:24 +0000) Optional(2019-03-27 22:31:17 +0000)

The code above works as expected.

use SSS instead of sss

for your case of yyyy-MM-dd'T'HH:mm:ss.sssZ and 2019-04-02T09:47:24.055Z output was :

Optional(2019-04-02 09:47:55 +0000) nil

look at minutes and seconds:)

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194