Swift - Converting JSON date to Swift compatible date

后端 未结 2 1782
天命终不由人
天命终不由人 2021-01-15 02:49

I am trying to convert a date in which the javascript code is generating the current date using the Date() function. But when I print it out, I am getting nil.

my co

相关标签:
2条回答
  • 2021-01-15 03:44

    Swift 4+

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let str = "2013-07-21T19:32:00Z"
    
    if let date = dateFormatter.date(from: str) {
        print(date)
    }
    

    Output: 2013-07-21 19:32:00 +0000

    0 讨论(0)
  • 2021-01-15 03:46

    The issue is that str and date2 two are not the same date format. str format is "yyyy-MM-dd'T'HH:mm:ssZ" while date2 format is "yyyy-MM-dd'T'HH:mm:ss.SSSZ". Besides that you should always set your dateFormatter's locale to "en_US_POSIX" when parsing fixed-format dates:

    let date2 = "2015-05-15T21:58:00.066Z"
    
    let dateFormatter = DateFormatter()
    dateFormatter.locale = .init(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    if let date = dateFormatter.date(from: date2) {
        print(date)  // "2015-05-15 21:58:00 +0000"
    }
    
    0 讨论(0)
提交回复
热议问题