Search code examples
swift

Can Date objects be compared between timezones in Swift


I have two date objects. One parsed from a server call in this form "2023-11-14T17:45:55Z" and a date object from adding minutes to .now.

I would like to write the code

serverDate > threeMinutesFromNow

But I want to be assured that this will work. I can't really find documentation on precisely HOW Date objects in swift implement comparable. If it's just by comparing timeIntervalSinceReferenceDate for the two AND that referenceDate is in a singular timezone I think this code is safe. But I am missing where I can check on this.


Solution

  • Date objects, themselves, simply do not have timezones.

    • That string, 2023-11-14T17:45:55Z, represents the same instant worldwide, i.e., 5:45pm UTC (aka GMT) on the 14th, whatever that is in your local timezone.
    • Likewise, Date.now.addingTimeInterval(3 * 60) (or however you are creating threeMinutesFromNow) represents a point in time worldwide. E.g., it is now 3:55pm in California, which is UTC-8, i.e., 11:55pm UTC; so 3 minutes from now is 11:58pm UTC.

    So, using those example Date objects, the > operator will compare these two Date objects, i.e., comparing 5:54pm UTC on the 14th to 11:58pm UTC today.