【发布时间】:2021-02-08 19:36:27
【问题描述】:
以下代码放在 Swift Xcode Playground 中:
let day = Calendar.current.date(from: DateComponents(calendar: .current, timeZone: .current, era: .none, year: 2020, month: 10, day: 1, hour: 1, minute: 1, second: 1, nanosecond: 1, weekday: .none, weekdayOrdinal: .none, quarter: .none, weekOfMonth: .none, weekOfYear: .none, yearForWeekOfYear: .none)) ?? Date()
print(day)
预计产出:2020-10-26 01:01:01 +0000
实际输出:2020-09-30 18:01:01 +0000
注意:运行日期()是 2020 年 10 月 26 日
以下代码打印出看似随机的日期是否有原因?这是一个快速的错误(使用 XCode 版本 11.6 Beta)吗?用日期组件实例化日期时我做错了什么吗?如何获得预期的输出?
谢谢
【问题讨论】:
-
不,这是正确的,将您的打印更改为
print(day.description(with: .current))以使用当前区域设置,与日历相同 -
与您的问题无关,但您可以简单地省略您不使用的组件。顺便说一句
DateComponents有一个date属性DateComponents(calendar: .current, year: 2020, month: 10, day: 1, hour: 1, minute: 1).date!