How to convert String to NSDate?

后端 未结 1 1069
轮回少年
轮回少年 2021-01-26 03:37

I have string that I received whenever there is new remote notifications.I\'m using parse for my Backend. And String that I retrieved come from \"createdAt\" column.

I\'

相关标签:
1条回答
  • 2021-01-26 04:01

    You are missing the milliseconds. Thus:

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

    Note, when converting from the date string to a NSDate, you shouldn't quote the Z. If you quote the Z, it will match the literal Z character, but won't correctly reflect that this date string is actually Zulu/GMT/UTC.


    If you want to create formatter that also goes the other way, converting NSDate objects to strings, in that case you should quote the Z, but in that case you must remember to explicitly set the timezone:

    dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    dateFormater.timeZone = NSTimeZone(forSecondsFromGMT: 0)
    

    By the way, don't forget to set the locale as per Apple Technical Q&A 1480.

    dateFormater.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    
    0 讨论(0)
提交回复
热议问题