首页 > 解决方案 > Swift 日期组件 .day 被忽略

问题描述

我试图找到这个月的第一天。在 SO 上发布了不同的解决方案(例如this

在分析它们时,似乎日组件被忽略了。
而不是返回该月的第一天

Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))!

它返回当前日期但更改月份:

(lldb) po Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))!
▿ 2019-02-28 23:00:00 +0000
  - timeIntervalSinceReferenceDate : 573087600.0

(lldb) po self
▿ 2019-03-28 01:09:17 +0000
  - timeIntervalSinceReferenceDate : 575428157.663583

我还研究了手动设置组件:

var components = Calendar.current.dateComponents([.year, .month, .day], from: self)
components.setValue(1, for: .day)
let value = Calendar.current.date(from: components)!

结果相同:

(lldb) po value
▿ 2019-02-28 23:00:00 +0000
  - timeIntervalSinceReferenceDate : 573087600.0

难道我做错了什么?或者这是日历中的错误?

Apple Swift version 5.0.1 (swiftlang-1001.0.82.4 clang-1001.0.46.5)
Target: x86_64-apple-darwin18.6.0

哦,如果这很有趣,我正在为 macOS 开发,但据我所知,这个 API 不受 Catalina 的影响。

标签: swiftdatecalendar

解决方案


你的代码很好。您有一个 2019 年 3 月的日期。您在当地时间午夜创建一个新日期,即 2019 年 3 月 1 日。到目前为止一切都很好。

唯一的问题是您对打印该日期的输出的误解。日期以 UTC 时间在调试器中打印。这就是+0000意思 - UTC 时间。您必须居住在 UTC+1 时区。

因此,您的当地时间 2019 年 3 月 1 日午夜与 2019 年 2 月 28 日 23:00 UTC 相同。这是同一时刻,只是显示在不同的时区。

简而言之,您的代码很好。


推荐阅读