swift - 为什么尝试在 iOS Swift 3 中使用 dateFormatter 时得到 nil?

标签 swift date null dateformatter

我尝试将字符串格式的日期转换为日期格式,如下所示:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"             
let date = dateFormatter.date(from: "2017-03-22")

但是得到零值。

我设置了

dateFormatter.locale = Locale(identifier: "en_US_POSIX") 

但不起作用...
请帮忙解决这个问题。

最佳答案

我想您的设备日历设置为与默认公历不同的日历,添加此行将解决问题:

dateFormatter.calendar = Calendar(identifier: .gregorian)

我还注意到您的日期没有嵌入任何时区,如果您有固定时区,也请添加这一行:

dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
// Replace "UTC" with your desired timezone

最终的代码如下:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"             
dateFormatter.calendar = Calendar(identifier: .gregorian)
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let date = dateFormatter.date(from: "2017-03-22")

关于swift - 为什么尝试在 iOS Swift 3 中使用 dateFormatter 时得到 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763734/

相关文章:

c - 如何在 fgetc 中的 C 字符串中存储重复的空字符?

sql - DB2 上周日到下周六的语句之间

dynamic - RollingFileAppender 中动态文件命名的 log4net 问题

swift - 优先级高于闭包

swift 3循环错误(获取变量并自行添加)

sql - 根据日期范围选择记录值

sql - 如何处理 Oracle SQL 中的无效日期

python - 将参数从批处理文件传递到 Python

ios - swift : UIPickerViewController delegates not called after Class-Extraction

ios - NSValue(CMTime : ) in swift 3?