【问题标题】:Why DatetimeComponents are no returning hours, minutes and seconds when converting GMT time为什么转换 GMT 时间时 DatetimeComponents 没有返回小时、分钟和秒
【发布时间】:2021-11-17 05:30:33
【问题描述】:

我将日期时间(2021-10-15 18:30:00 UTC,2021-10-15 18:30:00 +0000) 转换为datetime 组件,但缺少小时、分钟和秒

let changedDate = Calendar.current.date(byAdding: .day, value: -10, to: actualDate)!
var datcomp = Calendar.current.dateComponents([.year, .month, .day,.hour,.minute,.second], from: changedDate)
datcomp.timeZone = TimeZone(abbreviation: "GMT")

▿ 2021-10-15 18:30:00 +0000

  • timeIntervalSinceReferenceDate : 656015400.0

▿时区:GMT(固定)年:2021月:10日:11时:0分:0 second: 0 isLeapMonth: false ▿ timeZone : GMT (fixed) - 标识符:“GMT” - 种类:“固定” ▿ 缩写:可选 - 一些:“格林威治标准时间” - 秒从格林威治标准时间:0 - isDaylightSavingTime : 假

  • 年份:2021
  • 月:10
  • 天:11
  • 小时:0
  • 分钟:0
  • 秒:0
  • isLeapMonth:假

更多日志

实际日期:2021-09-26 18:30:00 +0000 更改日期:2021-09-21 18:30:00 +0000 日期计算:年:2021 月:9 日:22 小时:0 分钟:0 秒:0 isLeapMonth:false

【问题讨论】:

  • 什么是actualDate?它是如何创建/设置的?
  • 它来自 API
  • 当我看到 variable 的值时,它显示为 2021-10-15 18:30:00 UTC
  • 当我打印对象时,它显示为 2021-10-15 18:30:00 +0000
  • 我建议不要使用 DateComponents 来打印日期。只需Print(date)

标签: ios datetime nsdatecomponents gmt


【解决方案1】:

您的 API 以 UTC 格式发送日期时间。 你减去的天数也很好。 但问题是您使用的是日期时间组件。

Datetime 组件将根据您当前的设备设置给出日期时间对象。

就像你在印度一样。时区差异是 5:30,您的日期时间对象有 6:30 PM,因此它是 00:00:00

您使用其他时间不是 6:30 的数据,然后您将开始看到小时、分钟和秒

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 我打算用类似的东西来回答。我没有意识到 OP 在印度,时差为 5:30。接得好。我要补充一点,OP 中的 changedDat 实际上是他们应该使用的正确日期。
  • 是的,你是对的。 Date 与本地时区无关,而 DatetimeComponent 基于本地设备的日历、时区和语言环境
  • 感谢所有这些困惑都解决了。 ,我不知道 datetimecompents 会更改相对于当前时区的日期。整个混乱来自我的本地日历通知触发器没有触发本地通知。如果你们可以看看这个 (stackoverflow.com/q/69310525/15140177) 并找出为什么没有触发通知,我将不胜感激。
猜你喜欢
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 2012-01-06
相关资源
最近更新 更多