【问题标题】:Swift: How do you properly instantiate dates from selective date components?斯威夫特:你如何正确地从选择性日期组件中实例化日期?
【发布时间】: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!

标签: swift date types calendar


【解决方案1】:

这是因为您当前所在的 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)

【讨论】:

  • OP 说预期的输出是 Expected Output: 2020-10-26 01:01:01 +0000 这没有任何意义。无论如何,问题不在于输入。问题是他正在打印日期(UTC)而不是获取当前时区的日期表示。如果他想要 UTC,他为什么要指定当前时区?
  • @LeoDabus 是的。但他也希望输出具有+0000,它指的是UTC 时区。不确定这是不是故意的。
  • 他大概都不知道是什么意思
猜你喜欢
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
相关资源
最近更新 更多