//! THE one answer to "what does a clock in zone X read at this instant" — the //! port of `packages/core/src/engine/zonedClock.ts`. //! //! There were two implementations once, and that is why the TypeScript module //! exists: `newsSchedule.ts` read the wall clock with `hour12: false`, the //! recurrence engine grew its own reader using `hourCycle: "h23"`, and on //! Hermes an ignored `hourCycle` falls back to a twelve-hour clock whose //! `dayPeriod` the reader throws away — every hour from 13:00 to 23:00 read //! TWELVE HOURS LOW, silently. Two implementations of "what hour is it in zone //! X" is the same class of mistake as two implementations of "who wins" in the //! fold, and it lands in the same place: the phone and the server computing //! different instants for one occurrence, deriving different ids, and the //! person seeing everything twice. //! //! So this module is the only place in the Rust core that resolves a zone. //! //! **What replaces `Intl`.** The TypeScript asks `Intl.DateTimeFormat` (ICU's //! tzdata); this asks `chrono-tz` (the IANA tzdata compiled into the binary). //! Both read the same database, but they are two copies of it, so the tests //! pin 133 `zonedParts`/`zoneOffsetMs` readings and 32 `instantFromZoned` //! answers against what Node actually returned — across seven zones and every //! 2026 DST transition of the four the product cares about, plus a //! 45-minute-offset zone (Pacific/Chatham) and a southern-hemisphere one whose //! rule CHANGED in 2019 (America/Sao_Paulo, probed in 1999 when it still had //! DST). A tzdata version skew between ICU and this crate would show up there //! first. //! //! **What replaces `Date`.** Every instant is epoch milliseconds (`i64`); a //! pure library may not construct a clock. [`date_utc`] is ECMAScript's //! `Date.UTC` including its two surprises — the two-digit-year mapping and //! out-of-range component normalisation — because the recurrence engine leans //! on both. use chrono::{Datelike, Timelike}; use chrono_tz::Tz; /// A wall-clock reading in some zone. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct ZonedParts { pub year: i64, pub month: i64, pub day: i64, pub hour: i64, pub minute: i64, pub second: i64, } /// The failures the TypeScript raises as a `RangeError`. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum ZoneError { /// The TypeScript's sentence, verbatim. #[error("cotton: \"{0}\" is not a known time zone")] UnknownTimeZone(String), /// An instant outside what a calendar can render. The TypeScript cannot /// reach this case (a `Date` that far out is already `Invalid Date`); it /// exists so this module has no panic path. #[error("cotton: {0} is not an instant a calendar can read")] UnreadableInstant(i64), } /// Resolve a zone name, or say it is not one. fn zone_of(timezone: &str) -> Result { timezone .parse::() .map_err(|_| ZoneError::UnknownTimeZone(timezone.to_string())) } /// Read an instant's wall clock in `timezone`. /// /// The TypeScript THROWS on a field the formatter did not return, and says why: /// substituting a zero would be worse than failing, because a missing `hour` /// would silently read as midnight and the caller — deriving an occurrence id /// from the result — would mint a row at the wrong instant rather than a row at /// no instant. There is no partial-read case here (the calendar either renders /// or it does not), so the equivalent refusal is /// [`ZoneError::UnreadableInstant`]. pub fn zoned_parts(instant_ms: i64, timezone: &str) -> Result { let tz = zone_of(timezone)?; let local = chrono::DateTime::from_timestamp_millis(instant_ms) .ok_or(ZoneError::UnreadableInstant(instant_ms))? .with_timezone(&tz); Ok(ZonedParts { year: i64::from(local.year()), month: i64::from(local.month()), day: i64::from(local.day()), // `% 24` in the TypeScript, because a twelve-hour formatter can render // midnight as "24". `chrono` says 0..=23 already; the modulo is kept so // the two read as the same function. hour: i64::from(local.hour()) % 24, minute: i64::from(local.minute()), second: i64::from(local.second()), }) } /// The zone's offset from UTC at `instant_ms`, in milliseconds /// (positive = east). /// /// Derived the TypeScript's way rather than by asking the zone: read the local /// wall clock, ask what instant it would be if that clock were UTC, and take /// the difference. That IS the offset, DST included — and computing it from /// [`zoned_parts`] rather than from `chrono`'s own offset means the two /// functions can never disagree with each other, which is the property the /// TypeScript was buying. pub fn zone_offset_ms(instant_ms: i64, timezone: &str) -> Result { let parts = zoned_parts(instant_ms, timezone)?; let sub_second = instant_ms.rem_euclid(1000); let as_if_utc = date_utc( parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second, sub_second, ); Ok(as_if_utc - instant_ms) } /// The instant at which a clock in `timezone` reads these components. /// /// Two lookups, not one: the offset that applies at the naive guess is not /// necessarily the offset that applies at the answer — which is exactly what /// happens on a DST boundary, where the guess sits on one side and the real /// instant on the other. Iterating once settles it. /// /// A wall time that does not exist (inside a spring-forward gap) still resolves /// to a single deterministic instant, and a wall time that happens twice (in a /// fall-back overlap) resolves to one of them. WHICH one is not the point; /// that every runtime computes the SAME one is, because the occurrence id is /// derived from it. pub fn instant_from_zoned(parts: ZonedParts, ms: i64, timezone: &str) -> Result { let naive = date_utc( parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second, ms, ); let guess_offset = zone_offset_ms(naive, timezone)?; let candidate = naive - guess_offset; let real_offset = zone_offset_ms(candidate, timezone)?; Ok(if real_offset == guess_offset { candidate } else { naive - real_offset }) } // ───────────────────────────────────────────────────────────────────────────── // ECMAScript `Date.UTC`. // ───────────────────────────────────────────────────────────────────────────── /// `Date.UTC(year, month, day, hour, minute, second, ms)` — epoch /// milliseconds, with `month` ZERO-BASED as JavaScript has it. /// /// Two behaviours here are surprising and both are deliberate, because the /// recurrence engine leans on them: /// /// - **Two-digit years map into the twentieth century.** `Date.UTC(50, 0, 1)` /// is 1950, not year 50. No caller in this crate passes one, and porting the /// rule anyway costs one line and removes a way for the two implementations /// to differ. /// - **Components out of range NORMALISE rather than fail.** Month 12 is /// January of the next year, day 0 is the last day of the previous month, /// day 32 in a 31-day month is the 1st of the next. That is how the rrule /// engine walks a month boundary without special-casing it. /// /// The 8.64e15 clip that turns a far-out date into `NaN` is NOT ported: this /// returns the arithmetic answer. Nothing in the engines reaches it, and an /// `Option` on every arithmetic step would be noise standing in for a case /// that cannot occur. pub fn date_utc( year: i64, month: i64, day: i64, hour: i64, minute: i64, second: i64, ms: i64, ) -> i64 { let year = if (0..=99).contains(&year) { 1900 + year } else { year }; // `MakeDay`: the month index carries into the year. let ym = year + month.div_euclid(12); let mn = month.rem_euclid(12); let day_number = days_from_civil(ym, mn + 1, 1) + (day - 1); day_number * 86_400_000 + hour * 3_600_000 + minute * 60_000 + second * 1_000 + ms } /// Days since 1970-01-01 for a civil date — `Math.floor(Date.UTC(y, m-1, d) / /// 86_400_000)`, with `month` ONE-based here because every caller in the /// engines counts months the way a person does. pub fn day_number(year: i64, month: i64, day: i64) -> i64 { date_utc(year, month - 1, day, 0, 0, 0, 0).div_euclid(86_400_000) } /// The civil date `days` days after 1970-01-01, as `(year, month, day)` with /// `month` one-based — Howard Hinnant's `civil_from_days`, the inverse of /// [`day_number`]. /// /// (`zoned_clock_tests.rs` deliberately keeps its OWN copy of this arithmetic /// for its oracle: a test whose expectation is computed by the code under test /// is a green light wired to nothing, which is the mistake the TypeScript file /// records having made once already.) pub fn civil_from_days(days: i64) -> (i64, i64, i64) { let z = days + 719_468; let era = if z >= 0 { z } else { z - 146_096 } / 146_097; let day_of_era = z - era * 146_097; let year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; let year = year_of_era + era * 400; let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); let month_prime = (5 * day_of_year + 2) / 153; let day = day_of_year - (153 * month_prime + 2) / 5 + 1; let month = if month_prime < 10 { month_prime + 3 } else { month_prime - 9 }; (if month <= 2 { year + 1 } else { year }, month, day) } /// The weekday of a day number, Sunday = 0 … Saturday = 6 — /// `Date.prototype.getUTCDay`. 1970-01-01 was a Thursday. pub fn weekday_of_day_number(days: i64) -> i64 { (days + 4).rem_euclid(7) } /// How many days the given one-based month of the given year holds — /// `new Date(Date.UTC(year, month, 0)).getUTCDate()`, which reads the day /// BEFORE the first of the next month. pub fn days_in_month(year: i64, month: i64) -> i64 { civil_from_days(date_utc(year, month, 0, 0, 0, 0, 0).div_euclid(86_400_000)).2 } /// The day a yearly date (month, day) falls on in a named year, its day /// clamped into the month: a 29 February is kept on the 28th in a year /// without one. pub fn yearly_in_year(month: i64, day: i64, year: i64) -> (i64, i64, i64) { (year, month, day.min(days_in_month(year, month))) } /// The NEXT day a yearly date (month, day) comes round, counting `today` /// (year, month, day) as next — a yearly day is a day, not an instant. pub fn next_yearly_occurrence(month: i64, day: i64, today: (i64, i64, i64)) -> (i64, i64, i64) { let (year, this_month, this_day) = yearly_in_year(month, day, today.0); if day_number(year, this_month, this_day) >= day_number(today.0, today.1, today.2) { (year, this_month, this_day) } else { yearly_in_year(month, day, today.0 + 1) } } /// A calendar day with no instant and no zone: what a yearly date, a due day /// or a journal day is once its zone has been applied at the edge. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct CivilDate { pub year: i64, pub month: i64, pub day: i64, } impl CivilDate { /// Days since the epoch: the ordering key, and what makes a window in /// whole days a subtraction. pub fn day_number(self) -> i64 { day_number(self.year, self.month, self.day) } /// The day `days` days after 1970-01-01. pub fn of_day_number(days: i64) -> Self { let (year, month, day) = civil_from_days(days); Self { year, month, day } } pub fn tuple(self) -> (i64, i64, i64) { (self.year, self.month, self.day) } } impl From<(i64, i64, i64)> for CivilDate { fn from((year, month, day): (i64, i64, i64)) -> Self { Self { year, month, day } } } /// The day number of the calendar day an instant falls on in `timezone`: /// the one answer to "which day is this, there", for every caller that /// buckets instants by day. pub fn local_day(instant_ms: i64, timezone: &str) -> Result { let parts = zoned_parts(instant_ms, timezone)?; Ok(day_number(parts.year, parts.month, parts.day)) } /// A day number's `YYYY-MM-DD` key: the one spelling a stored calendar day /// takes (journal days, mood days, snapshot day values). pub fn day_key(day: i64) -> String { let (year, month, date) = civil_from_days(day); format!("{year:04}-{month:02}-{date:02}") } /// The `YYYY-MM-DD` key of the day an instant falls on in `timezone`. /// Refuses a zone it cannot read rather than falling back to UTC. pub fn local_day_key(instant_ms: i64, timezone: &str) -> Result { local_day(instant_ms, timezone).map(day_key) } /// The month and day a yearly date column holds: "1992-08-17", or /// "--08-17" when the year is not known. pub fn yearly_month_day(value: &str) -> Option<(i64, i64)> { let rest = value.strip_prefix("--").or_else(|| value.get(5..))?; let month = rest.get(0..2)?.parse().ok().filter(|month| (1..=12).contains(month))?; let day = rest.get(3..5)?.parse().ok().filter(|day| (1..=31).contains(day))?; Some((month, day)) } /// Days since 1970-01-01 for a proleptic Gregorian date (Howard Hinnant's /// `days_from_civil`), which is the calendar ECMAScript specifies. pub fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { let year = if month <= 2 { year - 1 } else { year }; let era = if year >= 0 { year } else { year - 399 } / 400; let year_of_era = year - era * 400; let month_prime = (month + 9) % 12; let day_of_year = (153 * month_prime + 2) / 5 + day - 1; let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; era * 146_097 + day_of_era - 719_468 } #[cfg(test)] #[path = "zoned_clock_tests.rs"] mod tests;