1

I have the following date string:

let dateString = "2018-06-24T14:52:32.647Z"

I'm trying to turn it into a date. However, it's not working with my DateFormatter.

I have extended DateFormatter to give a static formatter that I use throughout my app:

extension DateFormatter {
    static let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"
        return formatter
    }()
}

Then I say:

let date = DateFormatter.formatter.date(from: dateString)

It returns nil on one of my devices, but works on the rest of them. What am I doing wrong? Is it because I have three Zs at the end and I should have one?

LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
Tometoyou
  • 7,792
  • 12
  • 62
  • 108

3 Answers3

1

You need next date format:

extension DateFormatter {
static let formatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    return formatter
}()}
Lito
  • 2,309
  • 1
  • 23
  • 29
0

If it works in some device then it must be Language and Region problem.

Check In Setting -> General -> Language & Region, in which region working and which not.

Every region have different date formatter.

Manish Mahajan
  • 2,062
  • 1
  • 13
  • 19
  • This is sort of the right answer. I wasn't using the 24-hour time setting on my iPhone. Adding a locale to my date formatter solved the problem. – Tometoyou Jun 28 '18 at 12:23
0

You send wrong format to formatter

You have to change this code

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"

with

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
Ali Ihsan URAL
  • 1,894
  • 1
  • 20
  • 43