Swift日期组件。日期被忽略

Swift日期组件。日期被忽略,swift,date,calendar,Swift,Date,Calendar,我想找一个月的第一天。在SO上发布了不同的解决方案(例如) 在分析它们时,似乎忽略了日分量。 而不是在每月的第一天返回 Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))! 它返回当前日期,但更改月份: (lldb) po Calendar.current.date(from: Calendar.cu

我想找一个月的第一天。在SO上发布了不同的解决方案(例如)

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

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的影响。

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

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

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


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

谢谢您的回复。这是有道理的。让我偶然发现它的是计算四月的最后一天。上面的代码导致2019-03-31 22:00:00,这在您的解释之后是有意义的。根据上述链接中的代码计算的最后一天结果为:2019-04-28 00:30:35+0000。我不能从时区中推断出来,因为它不在30号附近。这也是我理解上的错误吗?同样的道理。你从四月的一天开始。你在当地时间午夜计算4月1日。这与UTC时间3月31日22:00时相同。由于夏令时的原因,现在有两个小时的不同。我同意3月31日是完全有意义的。就在最后一天,28号很奇怪。