如何处理多个日期格式? [英] How to handle multiple date formats?
问题描述
当我到达下面的df.date()行时,当这个格式的日期 2016-12-27 14:40:46 +0000
时,应用程序崩溃使用:
When I get to the df.date() line below, the app crashes when a date with this format 2016-12-27 14:40:46 +0000
is used:
致命错误:意外发现无法解开可选值
fatal error: unexpectedly found nil while unwrapping an Optional value
我也看到这样:
错误:执行中断,原因:EXC_BAD_INSTRUCTION
(code = EXC_I386_INVOP,subcode = 0x0)
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
我的字符串可以是这种格式
I have strings that can be in this format
12/27/2016
有时以这种格式
2016-12-27 14:40:46 +0000
以下是以上格式崩溃的代码片段:
Here is the code snippet that crashes on the above format:
let mydate = "12/27/2016" //this works but not the longer format
let df = DateFormatter()
df.dateFormat = "MM/dd/yyyy" //this is the format I want both dates to be in
newDate:Date = df.date(from: mydate)
如何使用基本的一个函数处理这两种格式? / p>
How do I handle both formats using basically one function?
推荐答案
检查日期字符串是否包含斜杠,并相应地设置日期格式:
Check if the date string contains a slash and set the date format accordingly:
if mydate.contains("/") {
df.dateFormat = "MM/dd/yyyy"
} else {
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
}
这篇关于如何处理多个日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!