Swift:您如何从选择性日期组件中正确实例化日期?
Swift: How do you properly instantiate dates from selective date components?
下面的代码放在Swift Xcode playgrounds:
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
注意:运行 的 Date() 是 2020 年 10 月 26 日
以下代码打印出看似随机的日期是否有原因?这是 swift 错误(使用 XCode 版本 11.6 Beta)吗?使用日期组件实例化日期时我做错了什么吗?如何获得预期的输出?
谢谢
这是因为您目前所在的 TimeZone
(.current
)。如果您希望输出为 2020-10-01 01:01:01 +0000
,您应该像这样使用 UTC 时区创建 DateComponents
:
let components = DateComponents(
calendar: .current,
timeZone: TimeZone(abbreviation: "UTC"),
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
)
let day = Calendar.current.date(from: components) ?? Date()
print(day)
下面的代码放在Swift Xcode playgrounds:
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
注意:运行 的 Date() 是 2020 年 10 月 26 日
以下代码打印出看似随机的日期是否有原因?这是 swift 错误(使用 XCode 版本 11.6 Beta)吗?使用日期组件实例化日期时我做错了什么吗?如何获得预期的输出?
谢谢
这是因为您目前所在的 TimeZone
(.current
)。如果您希望输出为 2020-10-01 01:01:01 +0000
,您应该像这样使用 UTC 时区创建 DateComponents
:
let components = DateComponents(
calendar: .current,
timeZone: TimeZone(abbreviation: "UTC"),
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
)
let day = Calendar.current.date(from: components) ?? Date()
print(day)