为什么 `ordinality(of: .day, in: .era, for: date)` 在不同时区的 2 个日期给出相同的结果?

Why does `ordinality(of: .day, in: .era, for: date)` give the same result for 2 dates in different time zones?

考虑以下代码:

import UIKit

let date = Date()

guard let nycTimeZone = TimeZone(abbreviation: "EST"),
  let nzTimeZone = TimeZone(abbreviation: "NZDT") else {
    fatalError()
}
var nycCalendar = Calendar(identifier: .gregorian)
nycCalendar.timeZone = nycTimeZone
var nzCalendar = Calendar(identifier: .gregorian)
nzCalendar.timeZone = nzTimeZone

let now = Date()

let nycDayOfEra = nycCalendar.ordinality(of: .day, in: .era, for: now)
let nycDayOfYear = nycCalendar.ordinality(of: .day, in: .year, for: now)

var nzDayOfEra = nzCalendar.ordinality(of: .day, in: .era, for: now)
var nzDayOfYear = nzCalendar.ordinality(of: .day, in: .year, for: now)

在我写这篇文章时,纽约时间和新西兰奥克兰时间给出了不同的日期。这就是我感兴趣的情况。

使用上面的代码,nycDayOfYear 和 nzDayOfYear 的结果不同(在撰写本文时,我得到 nycDayOfYear=42 和 nzDayOfYear=43。)

这是预期的,也是期望的。 (我正在努力回答一个 "how do I calculate the number of days of difference in two Dates evaluated in different time zones?" 问题。)

但是,要进行上述年中日期计算并计算出跨越年份边界的本地日期之间的差异天数,需要进行一系列混乱的调整。

因此我尝试使用 ordinality(of: .day, in: .era, for: date) 进行计算。

但是,无论用于凑合计算的日历的时区如何,基于日历纪元的计算都会给出相同的值。

这是为什么?

计算两个日期在不同的本地时区 之间的日历天数 差异的更简单方法是什么?就像我说的那样,我计算一年中某天的代码需要添加额外的逻辑来处理跨越日历年边界的日期。

请注意,这是一个不同于 "How many days difference is there between 2 dates" 的问题。在我的问题中,我希望两个日期都以不同的本地时区表示,并且我对每个日期值的日历日期的差异感兴趣。

Martin 关于在 long 间隔内进行日历计算并给出意想不到的结果的评论是关于为什么它不起作用的一个很好的答案。

我确实想出了代码来计算在特定时区表示的 2 个日期之间日历日期值的所需差异:

let date = Date()

guard let nycTimeZone = TimeZone(abbreviation: "EST"),
  let nzTimeZone = TimeZone(abbreviation: "NZDT") else {
    fatalError()
}
var nycCalendar = Calendar(identifier: .gregorian)
nycCalendar.timeZone = nycTimeZone
var nzCalendar = Calendar(identifier: .gregorian)
nzCalendar.timeZone = nzTimeZone

let now = Date()


let nycDateComponents = nycCalendar.dateComponents([.month, .day, .year], from: now)
let nzDateComponents = nzCalendar.dateComponents([.month, .day, .year], from: now)

let difference = Calendar.current.dateComponents([.day],
  from: nycDateComponents,
    to: nzDateComponents)

let daysDifference = difference.days

首先,我使用设置为特定时区的日历将 2 个日期转换为 month/day/year DateComponents 值。

然后我使用日历函数 dateComponents(_:from:to:),它可以让您计算 2 个 DateComponents 值之间的差异,无论您要使用什么单位来比较它们。 (天,在这种情况下)