简体   繁体   English

如何处理两种可能的日期格式?

[英]How to handle two possible date formats?

My app calls a web api that sometimes returns json dates in this format: 我的应用调用了一个Web API,有时会以这种格式返回json日期:

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

and sometimes in this format: 有时采用以下格式:

"2017-02-14T19:53:38.1173228Z"

I can use the following dateformat to convert the 2nd one to a Date object: 我可以使用以下日期格式将第二个日期格式转换为日期对象:

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

But of course it doesn't work for the 1st one. 但是,当然,它不适用于第一个。

I've tried utilities like https://github.com/melvitax/DateHelper to see if it will work, but I haven't found a way to convert a json date (in any format) into a Date object. 我已经尝试过使用https://github.com/melvitax/DateHelper之类的实用程序来查看其是否有效,但是我还没有找到将json日期(任何格式)转换为Date对象的方法。

Any recommendations? 有什么建议吗?

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. 另请注意,格式中的Z不是文字值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM