【问题标题】:Wrong date on setting Calendar timeZone to UTC将日历时区设置为 UTC 的日期错误
【发布时间】:2020-09-15 11:29:48
【问题描述】:

我在整个应用程序中使用 Date 对象,当我 NSLog 时它显示给我的值:

2020-05-24 22:00:00 +0000

我认为本地表示 25 日(- 1 表示夏季,-1 表示时区)。我想做一些日历日期比较:

var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "UTC")!
// In order to have start on Monday
calendar.firstWeekday = 2

使用这个日历,假设我想获取本周的开始日期:

extension Date
{
    var startOfWeek: Date {
        return Calendar.gregorian.date(from: Calendar.gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
    }
}

如果我是 NSLog:

Date().startOfWeek

它会告诉我:

2020-05-25 00:00:00 +0000

如果我禁用日历上的 timeZone 行,它会显示:

2020-05-24 22:00:00 +0000

我一直认为第二个是正确的 UTC 版本。我错了吗?因为我认为所有核心数据日期,所有日期都在第 2 版中。简而言之:如果我将日历设置为 UTC,我的日期比较是错误的。如果我不这样做,他们很好。所有这些时间日期都是 UTC。

【问题讨论】:

    标签: ios swift nsdate nscalendar


    【解决方案1】:

    你错了,因为 CoreData 日期不受时区影响。日期就是日期。将它们视为数值。当您将该值转换为日期和小时时,只有这样,才会应用 TimeZone。

    在您的示例中,一切都是正确的。对于 TimeZone 为 UTC 的日历,2020-05-25 00:00:00 +0000 是一周的开始。如果您使用其他 TimeZone 值(例如 Locale 中的默认值),则您的一周从 2020-05-24 22:00:00 +0000 开始。这意味着在您的 TimeZone 中,小时是 2020-05-25 00:00:00。

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 2017-10-10
      • 1970-01-01
      • 2014-12-27
      • 2020-09-29
      • 2019-09-07
      • 2015-03-06
      • 1970-01-01
      • 2015-11-13
      相关资源
      最近更新 更多