1

I am getting this date string from a API "2017-11-25T20:41:00.629Z"

I am trying to convert it into Date type, but I can't find the -> .629Z representation online

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

apparently this is not working and I get nil when I am converting the String into Date. I tried different things but .... !

Any idea ?

Thanks

P S
  • 527
  • 4
  • 18

2 Answers2

0

You can specify milliseconds using SSS for your date format with 3 digit milliseconds precision.

let dateString = "2017-11-25T20:41:00.629Z"
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
df.locale = Locale(identifier: "en_US_POSIX")
df.date(from: dateString) // "Nov 25, 2017 at 8:41 PM"
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • Why putting `Z` into quotes? That's just strange – Sulthan Dec 06 '17 at 13:06
  • 1
    This is wrong !!! Z means UTC time. If you scape the Z the date string will be interpreted as local time. – Leo Dabus Dec 06 '17 at 13:39
  • Besides that for fixed formats you need to set the DateFormatter locale to "en_US_POSIX" otherwise it might fail if the device locale setting uses 12h time format – Leo Dabus Dec 06 '17 at 13:41
  • **If you're working with fixed-format dates, first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences. en_US_POSIX is also invariant in time (if the US, at some point in the future, changes the way it formats dates, en_US will change to reflect the new behavior, but en_US_POSIX will not), and between platforms (works the same on iPhone OS as it does on OS X, and as it does on other platforms)** – Leo Dabus Dec 06 '17 at 13:50
  • @LeoDabus thanks for the input, updated my answer – Dávid Pásztor Dec 06 '17 at 14:28
  • The result shouldn’t be 8pm unless you are located at 0 seconds from gmt – Leo Dabus Dec 06 '17 at 14:31
  • 1
    @LeoDabus I am actually in the GMT time zone. – Dávid Pásztor Dec 06 '17 at 14:32
  • Can you provide a link that someone can find all the information that you mentioning above ? – P S Dec 07 '17 at 10:06
0

Just found it after aaaa loooot of time

"yyyy-MM-dd'T'HH:mm:ss'.'SSSz"

Thanks

P S
  • 527
  • 4
  • 18