What is a Date in Foundation, and what does it not contain?
Predict first
What does this print?
print(Date(timeIntervalSince1970: 0).timeIntervalSinceReferenceDate)
- 0.0
- -978307200.0
- 978307200.0
Predict first
Which of these does a Date store?
// A: an instant (seconds)
// B: year, month and day
// C: a time zone
- A
- B
- C
Mental model. A Date is a point on a ruler. “Tuesday at 3 pm” is what you get when you read that point off a particular local clock.
Date is a single instant on the timeline, stored as a Double count of seconds since 1 January 2001, 00:00 UTC (the reference date). It has no time zone, no calendar and no format. “March 10th” or “3 pm” only exist once you apply a Calendar and a TimeZone to it.
That is why a Date is safe to store and compare: < and == mean “earlier” and “exactly the same instant”. Because it is floating point, two Date() calls are almost never equal. Date() is also wall-clock time, so it can jump when the user or the network changes the clock.
The Unix epoch (1970) is 978,307,200 seconds before the reference date (2001), so it is negative.
Only the instant. Year, month and day come from a Calendar, and the zone from a TimeZone.
Common traps
- “A Date is in the local time zone.” It is zone-less. Printing one shows UTC because
descriptionpicks it, not because the date is “in” UTC. - Comparing dates for equality. They are floating point, so compare with a tolerance or compare calendar components instead.
They might follow up with
- What is the reference date? 1 January 2001 00:00 UTC.
timeIntervalSince1970converts to the Unix epoch. - Why not store local time strings? They lose the instant: “2024-03-10 02:30” does not exist in New York on the DST change.
Related questions
- 2.2.2 How do you handle time zones: what do you store, send and show?
- 2.2.9 How do you measure elapsed time, and how do you show a duration?
How do you handle time zones: what do you store, send and show? →