How to handle two possible date formats?

前端 未结 1 1028
栀梦
栀梦 2021-01-25 06:56

My app calls a web api that sometimes returns json dates in this format:

\"2017-01-18T10:49:00Z\"

and sometimes in this format:



        
相关标签:
1条回答
  • 2021-01-25 07:28

    Try both formats:

    let parser1 = DateFormatter()
    parser1.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    
    let parser2 = DateFormatter()
    parser2.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    
    func parse(_ dateString: String) -> Date? {
        let parsers = [parser1, parser2]
    
        for parser in parsers {
            if let result = parser.date(from: dateString) {
                return result
            }
        }
    
        return nil
    }
    
    print(parse("2017-01-18T10:49:00Z"))
    print(parse("2017-02-14T19:53:38.1173228Z"))
    

    Also note that the Z in the format is not a literal value.

    0 讨论(0)
提交回复
热议问题