如何处理两种可能的日期格式? [英] How to handle two possible date formats?
本文介绍了如何处理两种可能的日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的应用调用有时会以这种格式返回 json 日期的 Web api:
My app calls a web api that sometimes returns json dates in this format:
"2017-01-18T10:49:00Z"
有时采用这种格式:
"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.
我尝试过像 https://github.com/melvitax/DateHelper 这样的实用程序来查看如果它可以工作,但我还没有找到将 json 日期(任何格式)转换为 Date 对象的方法.
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.
有什么建议吗?
推荐答案
尝试两种格式:
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"))
另请注意,格式中的 Z
不是文字值.
Also note that the Z
in the format is not a literal value.
这篇关于如何处理两种可能的日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文