Swift 日期组件 .day 被忽略
Swift Date Components .day is being ignored
我正在尝试查找该月的第一天。 SO 上发布了不同的解决方案(例如 )
在分析它们时,似乎忽略了日期部分。
而不是返回该月的第一天
Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))!
它 returns 当前日期但更改了月份:
(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 相同。这是同一时刻,只是显示在不同的时区。
总之,你的代码没问题。
我正在尝试查找该月的第一天。 SO 上发布了不同的解决方案(例如
在分析它们时,似乎忽略了日期部分。
而不是返回该月的第一天
Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))!
它 returns 当前日期但更改了月份:
(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 相同。这是同一时刻,只是显示在不同的时区。
总之,你的代码没问题。