返回错误结果的日期函数

Date function returning incorrect result

我找不到适合我的等效答案eg

请看代码。我正在格式化从网络服务下载的传入字符串 (item[9])。

var cal_end_date: Date!

var dateFormatter = DateFormatter()

let tempEndDate = item[9]

print("item[9]", item[9]) // 20190331
print("tempEndDate", tempEndDate) //20190331

dateFormatter.dateFormat = "YYYYMMDD"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.autoupdatingCurrent

cal_end_date = dateFormatter.date(from:tempEndDate)!
print(#function, "cal_end_date:", cal_end_date!) //2019-01-31 05:00:00 +0000    

结束日期的月份有误!我已经通过 运行 具有固定日期的 playground 中的代码确认了此结果。我在这里做错了什么吗? Swift 5 有什么变化吗? 谢谢

您始终可以使用 nsdateformatter.com 检查您的格式化程序的 dateFormat 是否正确(在 Examples 旁边检查 Reference 显示每个 letter/letters 代表什么)。

在您的情况下,您必须注意 dateFormat 的区分大小写。日和年用小写字母表示

dateFormatter.dateFormat = "yyyyMMdd"