Skip to main content

nodejs/stdlib/
date.rs

1//! JavaScript `Date` (global constructor). A Date is a plain object tagged
2//! `@@native = "Date"` whose time value (milliseconds since the Unix epoch, or
3//! NaN for an invalid date) lives in a hidden `@@ms` field.
4//!
5//! The surface is implemented in full: `getTime`/`valueOf`, the
6//! `toISOString`/`toUTCString`/`toString`/`toDateString`/`toTimeString`
7//! renderings, the `toLocale*` forms with their options (`crate::datefmt`),
8//! the field getters, the component SETTERS, the Annex-B `getYear`/`setYear`,
9//! and the statics `Date.now`/`Date.parse`/`Date.UTC`. Local time is the
10//! process's zone, read through `localtime_r` as node reads `TZ`.
11
12use crate::host::{with_host, JsObj};
13use fusevm::Value;
14use indexmap::IndexMap;
15use std::time::{SystemTime, UNIX_EPOCH};
16
17pub const STATIC_METHODS: &[&str] = &["now", "parse", "UTC"];
18
19/// Every method `instance_call` below answers. `valueOf` and `toString` are on
20/// this list because `Object.prototype` has methods by those names too: without
21/// the entry, `host::call_method` hands a Date to `object_builtin_method` and
22/// `date.valueOf()` returns the Date itself instead of its time value (so `+d`
23/// and `d - 0` were `NaN`).
24pub const INSTANCE_METHODS: &[&str] = &[
25    "getTime",
26    "valueOf",
27    "toISOString",
28    "toJSON",
29    "toUTCString",
30    "toGMTString",
31    "toString",
32    "toDateString",
33    "toLocaleString",
34    "toLocaleDateString",
35    "toLocaleTimeString",
36    "getFullYear",
37    "getUTCFullYear",
38    "getMonth",
39    "getUTCMonth",
40    "getDate",
41    "getUTCDate",
42    "getDay",
43    "getUTCDay",
44    "getHours",
45    "getUTCHours",
46    "getMinutes",
47    "getUTCMinutes",
48    "getSeconds",
49    "getUTCSeconds",
50    "getMilliseconds",
51    "getUTCMilliseconds",
52    "getTimezoneOffset",
53    "toTimeString",
54    "setTime",
55    "setFullYear",
56    "setUTCFullYear",
57    "setMonth",
58    "setUTCMonth",
59    "setDate",
60    "setUTCDate",
61    "setHours",
62    "setUTCHours",
63    "setMinutes",
64    "setUTCMinutes",
65    "setSeconds",
66    "setUTCSeconds",
67    "setMilliseconds",
68    "setUTCMilliseconds",
69    "getYear",
70    "setYear",
71    // 21.4.4.45. A Date is the one builtin whose DEFAULT hint is `"string"`,
72    // which is why `date + 1` concatenates while `date - 1` subtracts. The
73    // coercion path already knew that, but the method itself was not exposed,
74    // so `date[Symbol.toPrimitive]` was not a function.
75    "@@toPrimitive",
76];
77
78const MS_PER_DAY: f64 = 86_400_000.0;
79const DAYS: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
80const MONTHS: [&str; 12] = [
81    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
82];
83
84/// Milliseconds since the Unix epoch, right now.
85fn now_ms() -> f64 {
86    SystemTime::now()
87        .duration_since(UNIX_EPOCH)
88        .map(|d| d.as_millis() as f64)
89        .unwrap_or(0.0)
90}
91
92/// Build a Date value carrying `ms` (NaN → an "Invalid Date").
93fn from_ms(ms: f64) -> Value {
94    with_host(|h| {
95        let mut m = IndexMap::new();
96        m.insert("@@native".into(), h.new_str("Date"));
97        m.insert("@@ms".into(), Value::Float(ms));
98        h.new_object(m)
99    })
100}
101
102/// The stored time value of a Date instance (NaN if not a Date).
103pub(crate) fn ms_of(recv: &Value) -> f64 {
104    with_host(|h| match h.get(recv) {
105        Some(JsObj::Object(p)) => p.get("@@ms").map(|v| h.to_number(v)).unwrap_or(f64::NAN),
106        _ => f64::NAN,
107    })
108}
109
110/// `new Date(...)`.
111pub fn construct(args: &[Value]) -> Result<Value, String> {
112    let ms = match args.len() {
113        0 => now_ms(),
114        1 => {
115            let a = &args[0];
116            // A string argument is parsed; anything else is coerced to a number
117            // (milliseconds). Another Date coerces via its time value.
118            if let Value::Str(_) = a {
119                parse_str(&with_host(|h| h.str_of(a)))
120            } else if with_host(|h| matches!(h.get(a), Some(JsObj::Str(_)))) {
121                parse_str(&with_host(|h| h.str_of(a)))
122            } else if super::native_tag(a).as_deref() == Some("Date") {
123                ms_of(a)
124            } else {
125                // 21.4.2.1 step 3.d is `ToNumber(v)` after `ToPrimitive`, and a
126                // SYMBOL refuses it — `new Date(sym)` produced an Invalid Date
127                // instead of throwing.
128                if with_host(|h| matches!(h.get(a), Some(crate::host::JsObj::Symbol { .. }))) {
129                    return Err(crate::host::type_error(
130                        "Cannot convert a Symbol value to a number",
131                    ));
132                }
133                // 21.4.2.1 step 3.c: `ToPrimitive(value)` first, and a string
134                // result is PARSED, a Date-string object included.
135                // The Date constructor reads `@@toPrimitive` itself and words a
136                // non-callable one as a bad PROPERTY, not as a bad callee.
137                if let Some(f) = crate::host::protocol_lookup(a, "@@toPrimitive")? {
138                    let bad = with_host(|h| !h.is_nullish(&f) && !crate::host::is_callable(h, &f));
139                    if bad {
140                        return Err(crate::host::type_error(&format!(
141                            "'{}' returned for property 'Symbol(Symbol.toPrimitive)' of object '{}' is not a function",
142                            crate::builtins::no_side_effects_string_pub(&f),
143                            crate::builtins::no_side_effects_string_pub(a)
144                        )));
145                    }
146                }
147                let prim = crate::host::to_primitive(a, "default")?;
148                if with_host(|h| h.as_str(&prim).is_some()) {
149                    parse_str(&with_host(|h| h.str_of(&prim)))
150                } else {
151                    crate::host::to_number_value(&prim)?
152                }
153            }
154        }
155        // (year, month[, day, hours, minutes, seconds, ms]) — LOCAL time
156        // (21.4.2.1 step 5.k: `UTC(MakeDate(...))`). It was taken as UTC, so
157        // under `TZ=America/New_York` `new Date(2024, 0, 31)` read back as
158        // 19:00 on the 30th, and `new Date(99, 0).getFullYear()` as 1998.
159        _ => {
160            let n = |i: usize, dflt: f64| {
161                args.get(i)
162                    .map(|v| with_host(|h| h.to_number(v)))
163                    .unwrap_or(dflt)
164            };
165            let mut year = n(0, f64::NAN);
166            // Years 0..99 map to 1900..1999 per the spec.
167            if (0.0..=99.0).contains(&year.trunc()) {
168                year = year.trunc() + 1900.0;
169            }
170            utc_from_local(utc_from_fields(
171                year,
172                n(1, 0.0),
173                n(2, 1.0),
174                n(3, 0.0),
175                n(4, 0.0),
176                n(5, 0.0),
177                n(6, 0.0),
178            ))
179        }
180    };
181    // TimeClip (21.4.1.31): a value beyond ±8.64e15 ms is not a representable
182    // date and becomes NaN. `new Date(8.64e15 + 1)` used to keep the raw number
183    // and print a real date where node prints `Invalid Date`.
184    Ok(from_ms(time_clip(ms)))
185}
186
187/// `Date()` called as a function (21.4.2.1 step 1): the current time as a string,
188/// ignoring every argument.
189pub fn call_as_function() -> Value {
190    let ms = time_clip(now_ms());
191    with_host(|h| h.new_str(format!("{} {}", date_string(local_ms(ms)), time_string(ms))))
192}
193
194/// `Date.now()` / `Date.parse(str)` / `Date.UTC(...)`.
195pub fn static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
196    Some(match method {
197        "now" => Ok(Value::Float(now_ms())),
198        "parse" => Ok(Value::Float(parse_str(&super::arg_str(args, 0)))),
199        "UTC" => {
200            let n = |i: usize, dflt: f64| {
201                args.get(i)
202                    .map(|v| with_host(|h| h.to_number(v)))
203                    .unwrap_or(dflt)
204            };
205            let mut year = n(0, f64::NAN);
206            if (0.0..=99.0).contains(&year.trunc()) {
207                year = year.trunc() + 1900.0;
208            }
209            Ok(Value::Float(time_clip(utc_from_fields(
210                year,
211                n(1, 0.0),
212                n(2, 1.0),
213                n(3, 0.0),
214                n(4, 0.0),
215                n(5, 0.0),
216                n(6, 0.0),
217            ))))
218        }
219        _ => return None,
220    })
221}
222
223/// Date instance methods.
224pub fn instance_call(recv: &Value, method: &str, _args: &[Value]) -> Result<Value, String> {
225    // Every `set*` argument is `ToNumber`d (21.4.4.x), which runs a user
226    // `valueOf` and can throw from it. The reads below are infallible and do no
227    // `ToPrimitive`, so `d.setFullYear({valueOf: () => 2020})` produced an
228    // Invalid Date.
229    let coerced: Vec<Value>;
230    let _args: &[Value] = if method.starts_with("set") {
231        let mut out = Vec::with_capacity(_args.len());
232        for a in _args {
233            let p = crate::host::to_primitive(a, "number")?;
234            out.push(Value::Float(with_host(|h| h.to_number(&p))));
235        }
236        coerced = out;
237        &coerced
238    } else {
239        _args
240    };
241    let ms = ms_of(recv);
242    let f = |ms: f64| ms; // readability alias for numeric returns
243    Ok(match method {
244        "getTime" | "valueOf" => Value::Float(f(ms)),
245        // `"string"` and `"default"` reach `toString` first, `"number"` reaches
246        // `valueOf` first — each read off the date, so an own override runs —
247        // and any other hint is a TypeError.
248        "@@toPrimitive" => return crate::builtins::date_to_primitive(recv, _args),
249        "toISOString" | "toJSON" => {
250            if ms.is_nan() {
251                if method == "toJSON" {
252                    with_host(|h| h.null())
253                } else {
254                    return Err(crate::host::range_error("Invalid time value"));
255                }
256            } else {
257                with_host(|h| h.new_str(iso_string(ms)))
258            }
259        }
260        "toUTCString" | "toGMTString" => with_host(|h| h.new_str(utc_string(ms))),
261        // `toString` (21.4.4.41) is NOT the RFC-7231 header form — that is
262        // `toUTCString`. It is `ToDateString`: the `toDateString` half, a space,
263        // then the `toTimeString` half. This used to answer `toUTCString`, so
264        // `String(date)` and `` `${date}` `` printed
265        // `Thu, 01 Jan 1970 00:00:00 GMT` where node prints
266        // `Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)`.
267        "toString" => with_host(|h| {
268            h.new_str(if ms.is_nan() {
269                "Invalid Date".into()
270            } else {
271                format!("{} {}", date_string(local_ms(ms)), time_string(ms))
272            })
273        }),
274        "toDateString" => with_host(|h| h.new_str(date_string(local_ms(ms)))),
275        // ECMA-402 `Date.prototype.toLocale{,Date,Time}String`: the options bag
276        // resolves to an ICU pattern (see `crate::datefmt`), in the en-US
277        // shape whatever `locales` says.
278        "toLocaleString" | "toLocaleDateString" | "toLocaleTimeString" => {
279            let required = match method {
280                "toLocaleDateString" => crate::datefmt::Required::Date,
281                "toLocaleTimeString" => crate::datefmt::Required::Time,
282                _ => crate::datefmt::Required::Any,
283            };
284            let opts = _args.get(1).cloned().unwrap_or(Value::Undef);
285            let s = crate::datefmt::date_to_locale(
286                ms,
287                &opts,
288                required,
289                &format!("Date.prototype.{method}"),
290            )?;
291            with_host(|h| h.new_str(s))
292        }
293        "getFullYear" => Value::Float(field(local_ms(ms), Field::Year)),
294        "getUTCFullYear" => Value::Float(field(ms, Field::Year)),
295        "getMonth" => Value::Float(field(local_ms(ms), Field::Month)),
296        "getUTCMonth" => Value::Float(field(ms, Field::Month)),
297        "getDate" => Value::Float(field(local_ms(ms), Field::Day)),
298        "getUTCDate" => Value::Float(field(ms, Field::Day)),
299        "getDay" => Value::Float(field(local_ms(ms), Field::Weekday)),
300        "getUTCDay" => Value::Float(field(ms, Field::Weekday)),
301        "getHours" => Value::Float(field(local_ms(ms), Field::Hours)),
302        "getUTCHours" => Value::Float(field(ms, Field::Hours)),
303        "getMinutes" => Value::Float(field(local_ms(ms), Field::Minutes)),
304        "getUTCMinutes" => Value::Float(field(ms, Field::Minutes)),
305        "getSeconds" => Value::Float(field(local_ms(ms), Field::Seconds)),
306        "getUTCSeconds" => Value::Float(field(ms, Field::Seconds)),
307        "getMilliseconds" => Value::Float(field(local_ms(ms), Field::Millis)),
308        "getUTCMilliseconds" => Value::Float(field(ms, Field::Millis)),
309        // 21.4.4.7: minutes WEST of UTC, so the sign is the opposite of the
310        // offset itself — `TZ=America/Detroit` reports 300, not -300.
311        // Computed as `(t - LocalTime(t)) / msPerMinute`, as written, so a zero
312        // offset is +0: negating it printed `-0` under `TZ=UTC`.
313        "getTimezoneOffset" => Value::Float(if ms.is_nan() {
314            f64::NAN
315        } else {
316            (ms - local_ms(ms)) / 60_000.0
317        }),
318        "toTimeString" => with_host(|h| h.new_str(time_string(ms))),
319        "setTime" => Value::Float(store_ms(recv, time_clip(super::arg_num(_args, 0)))),
320        // The component setters (21.4.4.20-21.4.4.28). Each takes its own field
321        // plus every LOWER-order one it can reach, defaulting the rest from the
322        // current time value, then rebuilds and TimeClips. `setUTCFullYear` and
323        // friends were absent entirely, so `d.setUTCFullYear(2000)` threw
324        // `is not a function` — a Date could be read but never modified except
325        // wholesale through `setTime`.
326        "setFullYear" => Value::Float(set_fields_local(recv, ms, 0, _args, false)),
327        "setUTCFullYear" => Value::Float(set_fields(recv, ms, 0, _args, false)),
328        "setMonth" => Value::Float(set_fields_local(recv, ms, 1, _args, false)),
329        "setUTCMonth" => Value::Float(set_fields(recv, ms, 1, _args, false)),
330        "setDate" => Value::Float(set_fields_local(recv, ms, 2, _args, false)),
331        "setUTCDate" => Value::Float(set_fields(recv, ms, 2, _args, false)),
332        "setHours" => Value::Float(set_fields_local(recv, ms, 3, _args, false)),
333        "setUTCHours" => Value::Float(set_fields(recv, ms, 3, _args, false)),
334        "setMinutes" => Value::Float(set_fields_local(recv, ms, 4, _args, false)),
335        "setUTCMinutes" => Value::Float(set_fields(recv, ms, 4, _args, false)),
336        "setSeconds" => Value::Float(set_fields_local(recv, ms, 5, _args, false)),
337        "setUTCSeconds" => Value::Float(set_fields(recv, ms, 5, _args, false)),
338        "setMilliseconds" => Value::Float(set_fields_local(recv, ms, 6, _args, false)),
339        "setUTCMilliseconds" => Value::Float(set_fields(recv, ms, 6, _args, false)),
340        // Annex B B.2.3.3 / B.2.3.4 — offset-from-1900 year accessors kept for
341        // legacy code. `setYear` maps 0..99 onto 1900..1999, which is the only
342        // way it differs from `setFullYear`.
343        // Annex B's pair is LOCAL, like `getFullYear`/`setFullYear`.
344        "getYear" => Value::Float(if ms.is_nan() {
345            f64::NAN
346        } else {
347            field(local_ms(ms), Field::Year) - 1900.0
348        }),
349        "setYear" => Value::Float(set_fields_local(recv, ms, 0, _args, true)),
350        _ => {
351            return Err(crate::host::type_error(&format!(
352                "date.{method} is not a function"
353            )))
354        }
355    })
356}
357
358// ── civil-calendar conversions (days-from-epoch ⇄ Y/M/D), UTC only ────────────
359
360enum Field {
361    Year,
362    Month,
363    Day,
364    Weekday,
365    Hours,
366    Minutes,
367    Seconds,
368    Millis,
369}
370
371/// Split a time value into (days-from-epoch, ms-within-day), flooring toward -∞
372/// so negative (pre-1970) times decompose correctly.
373pub(crate) fn split_day(ms: f64) -> (i64, i64) {
374    let day = (ms / MS_PER_DAY).floor();
375    let rem = ms - day * MS_PER_DAY;
376    (day as i64, rem as i64)
377}
378
379/// Convert a days-from-epoch count to (year, month 0-11, day 1-31) using
380/// Howard Hinnant's civil_from_days algorithm.
381pub(crate) fn civil_from_days(z: i64) -> (i64, i64, i64) {
382    let z = z + 719_468;
383    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
384    let doe = z - era * 146_097; // [0, 146096]
385    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; // [0, 399]
386    let y = yoe + era * 400;
387    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
388    let mp = (5 * doy + 2) / 153; // [0, 11]
389    let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
390    let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
391    (if m <= 2 { y + 1 } else { y }, m - 1, d)
392}
393
394/// Inverse: (year, month 0-11, day) → days from epoch.
395pub(crate) fn days_from_civil(y: i64, m0: i64, d: i64) -> i64 {
396    let m = m0 + 1;
397    let y = if m <= 2 { y - 1 } else { y };
398    let era = if y >= 0 { y } else { y - 399 } / 400;
399    let yoe = y - era * 400;
400    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
401    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
402    era * 146_097 + doe - 719_468
403}
404
405fn field(ms: f64, which: Field) -> f64 {
406    if ms.is_nan() {
407        return f64::NAN;
408    }
409    let (day, rem) = split_day(ms);
410    let (y, mo, d) = civil_from_days(day);
411    match which {
412        Field::Year => y as f64,
413        Field::Month => mo as f64,
414        Field::Day => d as f64,
415        // Weekday: 1970-01-01 (day 0) was a Thursday (4).
416        Field::Weekday => (((day % 7) + 4 + 7) % 7) as f64,
417        Field::Hours => (rem / 3_600_000) as f64,
418        Field::Minutes => (rem / 60_000 % 60) as f64,
419        Field::Seconds => (rem / 1000 % 60) as f64,
420        Field::Millis => (rem % 1000) as f64,
421    }
422}
423
424/// Assemble a UTC time value from broken-down fields (with month/day overflow
425/// normalized the way JS does, e.g. month 12 rolls into the next year).
426fn utc_from_fields(y: f64, mo: f64, d: f64, h: f64, mi: f64, s: f64, ms: f64) -> f64 {
427    // MakeDay / MakeTime (21.4.1.28-29): a non-finite field is NaN, and every
428    // field is `ToIntegerOrInfinity`d first — so `new Date(2024, 0, 1, 1.5)` is
429    // 01:00, not 01:30, and `Date.UTC(1970, 0, 1, 0, 0, 0, 0.9)` is 0.
430    if [y, mo, d, h, mi, s, ms].iter().any(|v| !v.is_finite()) {
431        return f64::NAN;
432    }
433    let [y, mo, d, h, mi, s, ms] = [y, mo, d, h, mi, s, ms].map(f64::trunc);
434    // Normalize month into 0..11, carrying into the year.
435    let total_months = y as i64 * 12 + mo as i64;
436    let year = total_months.div_euclid(12);
437    let month = total_months.rem_euclid(12);
438    let days = days_from_civil(year, month, d as i64);
439    days as f64 * MS_PER_DAY + h * 3_600_000.0 + mi * 60_000.0 + s * 1000.0 + ms
440}
441
442/// `Wed, 21 Oct 2015 07:28:00 GMT` — the RFC-7231 IMF-fixdate HTTP header form.
443/// The zone offset in MILLISECONDS east of UTC that applies at `ms`, from the
444/// C library's `localtime_r` — which reads `TZ` exactly as node does and is
445/// DST-aware per timestamp rather than per zone.
446///
447/// Everything local used to be UTC: `getTimezoneOffset()` answered 0, each
448/// local getter shared its arm with the `getUTC*` one, and `toString` rendered
449/// the UTC wall clock. Under `TZ=America/Detroit` that made
450/// `new Date(0).getMonth()` 0 where node says 11. The parity harness pins
451/// `TZ=UTC` for both sides, which is why no record ever caught it.
452#[cfg(unix)]
453pub(crate) fn zone_offset_ms(ms: f64) -> f64 {
454    if !ms.is_finite() {
455        return 0.0;
456    }
457    // `localtime_r` takes SECONDS; flooring keeps a pre-epoch timestamp in the
458    // right second rather than rounding it toward zero.
459    let secs = (ms / 1000.0).floor() as i64;
460    let t = secs as libc::time_t;
461    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
462    // SAFETY: `localtime_r` writes into the caller's `tm` and reads only `t`.
463    let ok = unsafe { !libc::localtime_r(&t, &mut tm).is_null() };
464    if !ok {
465        return 0.0;
466    }
467    tm.tm_gmtoff as f64 * 1000.0
468}
469
470#[cfg(not(unix))]
471pub(crate) fn zone_offset_ms(_ms: f64) -> f64 {
472    0.0
473}
474
475/// The local wall-clock time value for `ms` — what every local getter reads its
476/// fields out of.
477fn local_ms(ms: f64) -> f64 {
478    ms + zone_offset_ms(ms)
479}
480
481/// The inverse: a local wall-clock time value back to a timestamp.
482///
483/// The offset depends on the instant, so one lookup is not enough near a DST
484/// transition. Two candidates are built — using the offset at the naive guess
485/// and at the corrected one — and the one that reads BACK as the requested
486/// local time wins. A spring-forward GAP has no such candidate, because the
487/// wall clock never showed that time; 21.4.1.26 leaves the choice to the
488/// implementation and V8 takes the offset from BEFORE the transition, which
489/// pushes the result past it: local 02:30 on a spring-forward day is 03:30.
490fn utc_from_local(local: f64) -> f64 {
491    if !local.is_finite() {
492        return local;
493    }
494    let off_naive = zone_offset_ms(local);
495    let cand_a = local - off_naive;
496    let off_corrected = zone_offset_ms(cand_a);
497    if off_corrected == off_naive {
498        return cand_a;
499    }
500    let cand_b = local - off_corrected;
501    if local_ms(cand_b) == local {
502        return cand_b;
503    }
504    if local_ms(cand_a) == local {
505        return cand_a;
506    }
507    local - off_naive.min(off_corrected)
508}
509
510fn utc_string(ms: f64) -> String {
511    if ms.is_nan() {
512        return "Invalid Date".into();
513    }
514    let (day, _) = split_day(ms);
515    let (y, mo, d) = civil_from_days(day);
516    let wd = (((day % 7) + 4 + 7) % 7) as usize;
517    format!(
518        "{}, {:02} {} {} {:02}:{:02}:{:02} GMT",
519        DAYS[wd],
520        d,
521        MONTHS[mo as usize],
522        year_text(y),
523        field(ms, Field::Hours) as i64,
524        field(ms, Field::Minutes) as i64,
525        field(ms, Field::Seconds) as i64,
526    )
527}
528
529/// `00:00:00 GMT+0000 (Coordinated Universal Time)` — the `toTimeString` form
530/// (21.4.4.42 TimeString + TimeZoneString). The clock is LOCAL and the offset
531/// is the zone's real one; both were fixed at UTC before.
532///
533/// The parenthetical is the zone's LONG name, which node takes from ICU
534/// (`GMT-0500 (Eastern Standard Time)`); see [`zone_name`].
535fn time_string(ms: f64) -> String {
536    if ms.is_nan() {
537        return "Invalid Date".into();
538    }
539    let local = local_ms(ms);
540    let off_min = (zone_offset_ms(ms) / 60_000.0) as i64;
541    let sign = if off_min < 0 { '-' } else { '+' };
542    let abs = off_min.abs();
543    format!(
544        "{:02}:{:02}:{:02} GMT{}{:02}{:02} ({})",
545        field(local, Field::Hours) as i64,
546        field(local, Field::Minutes) as i64,
547        field(local, Field::Seconds) as i64,
548        sign,
549        abs / 60,
550        abs % 60,
551        zone_name(ms),
552    )
553}
554
555/// The zone's display name for `toString`: V8's `LocalTimezone`. It asks ICU
556/// (`TimeZone::getDisplayName(isDst, LONG)`) for the zone's long specific name
557/// through the metazone the zone belongs to NOW, so a 1938 date in Tokyo is
558/// still `Japan Standard Time`; `isDst` is whether the instant has a daylight
559/// offset, which V8 computes for an instant outside 1970..2038 at its
560/// equivalent time ([`v8_equivalent_time`]). A zone whose metazone has no such
561/// name (`Europe/London` in winter) is the localized GMT format of the zone's
562/// CURRENT raw offset, plus an hour when daylight in a zone that still keeps
563/// daylight time — `Asia/Damascus` is `GMT+03:00` for a 1975 date whose own
564/// offset was +2.
565///
566/// Without a resolvable zone id (`TZ` holding a POSIX rule), UTC is spelled
567/// out and anything else falls back to the abbreviation `localtime_r` reports.
568fn zone_name(ms: f64) -> String {
569    let Some((id, tz)) =
570        crate::tznames::local_zone_id().and_then(|id| crate::tzif::load(&id).map(|tz| (id, tz)))
571    else {
572        if zone_offset_ms(ms) == 0.0 {
573            return "Coordinated Universal Time".into();
574        }
575        return zone_abbrev(ms).unwrap_or_else(|| "Coordinated Universal Time".into());
576    };
577    let dst = tz.at((v8_equivalent_time(ms) / 1000.0).floor() as i64).dst;
578    let now = std::time::SystemTime::now()
579        .duration_since(std::time::UNIX_EPOCH)
580        .map_or(0, |d| d.as_secs() as i64);
581    if let Some(name) = crate::tznames::specific_name(&id, now, dst, true) {
582        return name.to_string();
583    }
584    // The raw offset and the daylight savings in force around now (half a
585    // year either side). ICU adds the savings only when the zone still uses
586    // daylight time (`useDaylightTime`); they are not always an hour
587    // (`Antarctica/Troll` saves two).
588    let around: Vec<_> = [now - 15_778_800, now, now + 15_778_800]
589        .iter()
590        .map(|&t| tz.at(t))
591        .collect();
592    let raw = around
593        .iter()
594        .find(|t| !t.dst)
595        .map_or(around[1].offset, |t| t.offset);
596    let savings = around.iter().find(|t| t.dst).map_or(0, |t| t.offset - raw);
597    let off_min = (raw + if dst { savings } else { 0 }) / 60;
598    let sign = if off_min < 0 { '-' } else { '+' };
599    format!(
600        "GMT{sign}{:02}:{:02}",
601        off_min.abs() / 60,
602        off_min.abs() % 60
603    )
604}
605
606/// V8's `DateCache::EquivalentTime`: an instant before 1970 or past 2038 moved
607/// to the same month, day and time of a year in 2008..2037 that starts on the
608/// same weekday and has the same leap-ness. V8 asks for daylight time there.
609fn v8_equivalent_time(ms: f64) -> f64 {
610    const MAX_EPOCH_MS: f64 = i32::MAX as f64 * 1000.0;
611    if (0.0..=MAX_EPOCH_MS).contains(&ms) {
612        return ms;
613    }
614    let (days, within) = split_day(ms);
615    let (year, month, day) = civil_from_days(days);
616    let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
617    let week_day = (days_from_civil(year, 0, 1) + 4).rem_euclid(7);
618    let recent = if leap { 1956 } else { 1967 } + (week_day * 12) % 28;
619    let equivalent = 2008 + (recent + 3 * 28 - 2008) % 28;
620    (days_from_civil(equivalent, month, day) as f64) * MS_PER_DAY + within as f64
621}
622
623/// The local zone's abbreviation at `ms` (`EST`, `EDT`, `UTC`), as
624/// `localtime_r` reports it.
625#[cfg(unix)]
626pub(crate) fn zone_abbrev(ms: f64) -> Option<String> {
627    let secs = (ms / 1000.0).floor() as i64;
628    let t = secs as libc::time_t;
629    let mut tm: libc::tm = unsafe { std::mem::zeroed() };
630    // SAFETY: as in `zone_offset_ms`.
631    if unsafe { libc::localtime_r(&t, &mut tm).is_null() } || tm.tm_zone.is_null() {
632        return None;
633    }
634    // SAFETY: `tm_zone` points at a static zone-name string owned by libc.
635    let z = unsafe { std::ffi::CStr::from_ptr(tm.tm_zone) };
636    Some(z.to_string_lossy().into_owned())
637}
638
639#[cfg(not(unix))]
640pub(crate) fn zone_abbrev(_ms: f64) -> Option<String> {
641    None
642}
643
644/// TimeClip (21.4.1.31): a time value more than 8.64e15 ms from the epoch is not
645/// representable and becomes NaN; anything else truncates toward zero.
646///
647/// Without this a `new Date(8.64e15 + 1)` kept the out-of-range value and
648/// printed a real date (`Sat, 13 Sep 275760 …`) where node prints
649/// `Invalid Date`, so the boundary every date-range check relies on was absent.
650fn time_clip(ms: f64) -> f64 {
651    if !ms.is_finite() || ms.abs() > 8.64e15 {
652        return f64::NAN;
653    }
654    // `+ 0.0` turns a truncated `-0.5` into `+0`: TimeClip yields a +0 time
655    // value, never -0.
656    ms.trunc() + 0.0
657}
658
659/// Write a time value into the receiver's hidden `@@ms` slot, returning it (as
660/// every mutator does).
661fn store_ms(recv: &Value, ms: f64) -> f64 {
662    with_host(|h| {
663        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
664            p.insert("@@ms".into(), Value::Float(ms));
665        }
666    });
667    ms
668}
669
670/// The shared body of every component setter.
671///
672/// `start` indexes the field the setter names within
673/// `[year, month, date, hours, minutes, seconds, ms]`; the setter consumes that
674/// field and every LOWER-order one in its own group (date fields 0..2, time
675/// fields 3..6), defaulting anything not supplied from the current time value.
676///
677/// `legacy_year` applies Annex B `setYear`'s 0..99 → 1900..1999 mapping.
678///
679/// NaN handling follows the spec's split: `setFullYear` on an invalid date
680/// treats the time value as +0 and so can REVIVE it (21.4.4.21 step 2), while
681/// every other setter leaves an invalid date invalid.
682/// `set_fields` on the LOCAL wall clock: read the current fields in local time,
683/// replace the ones given, then convert the result back to a timestamp.
684fn set_fields_local(recv: &Value, ms: f64, start: usize, args: &[Value], legacy_year: bool) -> f64 {
685    if ms.is_nan() && start != 0 {
686        return store_ms(recv, f64::NAN);
687    }
688    let local = set_fields_value(local_ms(ms), start, args, legacy_year);
689    store_ms(recv, time_clip(utc_from_local(local)))
690}
691
692fn set_fields(recv: &Value, ms: f64, start: usize, args: &[Value], legacy_year: bool) -> f64 {
693    if ms.is_nan() && start != 0 {
694        return store_ms(recv, f64::NAN);
695    }
696    store_ms(
697        recv,
698        time_clip(set_fields_value(ms, start, args, legacy_year)),
699    )
700}
701
702/// The field replacement itself, on whatever time value it is handed — the
703/// local wall clock for a `setHours`, the timestamp for a `setUTCHours`. Split
704/// out so the two differ only in what they pass in and what they do with the
705/// result.
706fn set_fields_value(ms: f64, start: usize, args: &[Value], legacy_year: bool) -> f64 {
707    let base = if ms.is_nan() {
708        0.0 // setFullYear/setYear on an Invalid Date starts from the epoch.
709    } else {
710        ms
711    };
712    let mut f = [
713        field(base, Field::Year),
714        field(base, Field::Month),
715        field(base, Field::Day),
716        field(base, Field::Hours),
717        field(base, Field::Minutes),
718        field(base, Field::Seconds),
719        field(base, Field::Millis),
720    ];
721    // A date setter reaches at most field 2; a time setter at most field 6.
722    let end = if start < 3 { 3 } else { 7 };
723    for (i, slot) in f.iter_mut().enumerate().take(end).skip(start) {
724        match args.get(i - start) {
725            Some(v) => *slot = with_host(|h| h.to_number(v)).trunc(),
726            // The first argument is required: `setUTCMinutes()` is
727            // `ToNumber(undefined)`, NaN, and so an Invalid Date.
728            None if i == start => *slot = f64::NAN,
729            None => break,
730        }
731    }
732    if legacy_year && (0.0..=99.0).contains(&f[0]) {
733        f[0] += 1900.0;
734    }
735    utc_from_fields(f[0], f[1], f[2], f[3], f[4], f[5], f[6])
736}
737
738/// The year of the human-readable forms (`toString`, `toDateString`,
739/// `toUTCString`): at least four digits, with a `-` OUTSIDE the padding, so year
740/// -1 is `-0001`. Rust's `{:04}` counts the sign inside the width and gives
741/// `-001`.
742fn year_text(y: i64) -> String {
743    format!("{}{:04}", if y < 0 { "-" } else { "" }, y.abs())
744}
745
746/// `Wed Oct 21 2015` — the `toDateString` form.
747fn date_string(ms: f64) -> String {
748    if ms.is_nan() {
749        return "Invalid Date".into();
750    }
751    let (day, _) = split_day(ms);
752    let (y, mo, d) = civil_from_days(day);
753    let wd = (((day % 7) + 4 + 7) % 7) as usize;
754    format!(
755        "{} {} {:02} {}",
756        DAYS[wd],
757        MONTHS[mo as usize],
758        d,
759        year_text(y)
760    )
761}
762
763/// The year field of an ISO-8601 date (21.4.4.36 `Date.prototype.toISOString`).
764///
765/// Years 0..=9999 are four digits; anything outside that range uses the EXPANDED
766/// form — an explicit sign and exactly six digits, `+275760` / `-000001`. A bare
767/// `{:04}` gets both wrong, since Rust counts the sign inside the width (`-1`
768/// formats as `-001`) and never emits `+`.
769fn iso_year(y: i64) -> String {
770    if (0..=9999).contains(&y) {
771        return format!("{y:04}");
772    }
773    let sign = if y < 0 { '-' } else { '+' };
774    format!("{sign}{:06}", y.abs())
775}
776
777/// `2015-10-21T07:28:00.000Z` — the ISO-8601 / `toISOString` form.
778fn iso_string(ms: f64) -> String {
779    let (day, _) = split_day(ms);
780    let (y, mo, d) = civil_from_days(day);
781    format!(
782        "{}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
783        iso_year(y),
784        mo + 1,
785        d,
786        field(ms, Field::Hours) as i64,
787        field(ms, Field::Minutes) as i64,
788        field(ms, Field::Seconds) as i64,
789        field(ms, Field::Millis) as i64,
790    )
791}
792
793/// Parse a date string: the Date Time String Format first ([`parse_iso`]),
794/// then the free-form fallback every engine keeps ([`parse_legacy`]). NaN on
795/// anything neither accepts — the "Invalid Date" contract.
796///
797/// The string is not trimmed first: V8 hands `" 2024-01-01 "` to the fallback,
798/// which reads it as LOCAL midnight rather than the format's UTC one.
799fn parse_str(s: &str) -> f64 {
800    time_clip(parse_iso(s).or_else(|| parse_legacy(s)).unwrap_or(f64::NAN))
801}
802
803/// The Date Time String Format (21.4.1.32): `YYYY[-MM[-DD]]`, optionally
804/// followed by `THH:mm[:ss[.sss]]`, optionally followed by a zone — `Z` or
805/// `±HH:mm` (V8 also takes `±HHmm`). The year may be the expanded `±YYYYYY`.
806///
807/// A date-only form is UTC; a date-time form WITHOUT a zone is LOCAL time
808/// (21.4.3.2 via the format's own note), which is why `"2024-01-01T10:20"` is
809/// 15:20Z under `TZ=America/New_York`. The offset used to be dropped entirely:
810/// `"…30.123+01:00"` read the fraction as `123` and ignored the rest, and
811/// `"…00+05:30"` failed to parse. Fields out of range (`T25:00`, `T10:60`, a
812/// month of 13) are NaN, as in V8; a day up to 31 rolls over as V8's does
813/// (`2023-02-29` is March 1).
814fn parse_iso(s: &str) -> Option<f64> {
815    let b = s.as_bytes();
816    let mut i = 0;
817    // `n` ASCII digits at the cursor, as a number.
818    let digits = |i: &mut usize, n: usize| -> Option<i64> {
819        let end = *i + n;
820        let part = b.get(*i..end)?;
821        if !part.iter().all(u8::is_ascii_digit) {
822            return None;
823        }
824        *i = end;
825        std::str::from_utf8(part).ok()?.parse().ok()
826    };
827    let year = match b.first()? {
828        sign @ (b'+' | b'-') => {
829            i = 1;
830            let y = digits(&mut i, 6)?;
831            // `-000000` is the one spelling the format forbids.
832            if *sign == b'-' && y == 0 {
833                return None;
834            }
835            if *sign == b'-' {
836                -y
837            } else {
838                y
839            }
840        }
841        _ => digits(&mut i, 4)?,
842    };
843    let (mut month, mut day) = (1, 1);
844    if b.get(i) == Some(&b'-') {
845        i += 1;
846        month = digits(&mut i, 2)?;
847        if b.get(i) == Some(&b'-') {
848            i += 1;
849            day = digits(&mut i, 2)?;
850        }
851    }
852    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
853        return None;
854    }
855    let date = days_from_civil(year, month - 1, day) as f64 * MS_PER_DAY;
856    // A date-only form, bare or with `Z`, is UTC.
857    match b.get(i) {
858        None => return Some(date),
859        Some(b'Z' | b'z') if i + 1 == b.len() => return Some(date),
860        Some(b'T' | b't' | b' ') => i += 1,
861        Some(_) => return None,
862    }
863    let h = digits(&mut i, 2)?;
864    if b.get(i) != Some(&b':') {
865        return None;
866    }
867    i += 1;
868    let mi = digits(&mut i, 2)?;
869    let (mut sec, mut milli) = (0, 0);
870    if b.get(i) == Some(&b':') {
871        i += 1;
872        sec = digits(&mut i, 2)?;
873        if b.get(i) == Some(&b'.') {
874            i += 1;
875            let start = i;
876            while b.get(i).is_some_and(u8::is_ascii_digit) {
877                i += 1;
878            }
879            if i == start {
880                return None;
881            }
882            // Only the milliseconds are kept; further digits are truncated.
883            let frac = &s[start..i.min(start + 3)];
884            milli = format!("{frac:0<3}").parse().ok()?;
885        }
886    }
887    // `24:00` is the end of the day and nothing past it is.
888    if h > 24 || mi > 59 || sec > 59 || (h == 24 && (mi, sec, milli) != (0, 0, 0)) {
889        return None;
890    }
891    let wall =
892        date + h as f64 * 3_600_000.0 + mi as f64 * 60_000.0 + sec as f64 * 1000.0 + milli as f64;
893    let offset = match b.get(i) {
894        None => return Some(utc_from_local(wall)),
895        Some(b'Z' | b'z') if i + 1 == b.len() => 0.0,
896        Some(sign @ (b'+' | b'-')) => {
897            let sign = if *sign == b'-' { -1.0 } else { 1.0 };
898            i += 1;
899            let oh = digits(&mut i, 2)?;
900            if b.get(i) == Some(&b':') {
901                i += 1;
902            }
903            let om = digits(&mut i, 2)?;
904            if i != b.len() || oh > 23 || om > 59 {
905                return None;
906            }
907            sign * (oh as f64 * 3_600_000.0 + om as f64 * 60_000.0)
908        }
909        Some(_) => return None,
910    };
911    Some(wall - offset)
912}
913
914/// One token of a free-form date string, as V8's `DateStringTokenizer` splits
915/// it: a run of digits (with its length, which decides how an offset reads), a
916/// run of letters, one other character, or white space. A parenthesized
917/// comment — `(Eastern Standard Time)` — is skipped whole.
918#[derive(Clone, Copy, PartialEq)]
919enum Tok<'a> {
920    Num(i64, usize),
921    Word(&'a str),
922    Sym(u8),
923    Space,
924    End,
925}
926
927struct Toks<'a> {
928    s: &'a str,
929    i: usize,
930}
931
932impl<'a> Toks<'a> {
933    fn next(&mut self) -> Tok<'a> {
934        let b = self.s.as_bytes();
935        let Some(&c) = b.get(self.i) else {
936            return Tok::End;
937        };
938        let start = self.i;
939        let run = |i: &mut usize, f: fn(&u8) -> bool| {
940            while b.get(*i).is_some_and(f) {
941                *i += 1;
942            }
943        };
944        if c.is_ascii_digit() {
945            run(&mut self.i, u8::is_ascii_digit);
946            let text = &self.s[start..self.i];
947            // A number too long for any field is still one token; its value
948            // only has to be large enough to fail every range check.
949            return Tok::Num(text.parse().unwrap_or(i64::MAX), text.len());
950        }
951        if c.is_ascii_alphabetic() {
952            run(&mut self.i, u8::is_ascii_alphabetic);
953            return Tok::Word(&self.s[start..self.i]);
954        }
955        if c.is_ascii_whitespace() {
956            run(&mut self.i, u8::is_ascii_whitespace);
957            return Tok::Space;
958        }
959        if c == b'(' {
960            let mut depth = 0;
961            while let Some(&c) = b.get(self.i) {
962                self.i += 1;
963                match c {
964                    b'(' => depth += 1,
965                    b')' => {
966                        depth -= 1;
967                        if depth == 0 {
968                            break;
969                        }
970                    }
971                    _ => {}
972                }
973            }
974            return Tok::Space;
975        }
976        // One character, whole: a non-ASCII one is ignored like any symbol.
977        let len = self.s[start..].chars().next().map_or(1, char::len_utf8);
978        self.i += len;
979        Tok::Sym(if len == 1 { c } else { 0 })
980    }
981
982    fn peek(&self) -> Tok<'a> {
983        Toks {
984            s: self.s,
985            i: self.i,
986        }
987        .next()
988    }
989
990    fn skip(&mut self, sym: u8) -> bool {
991        let taken = self.peek() == Tok::Sym(sym);
992        if taken {
993            self.next();
994        }
995        taken
996    }
997}
998
999/// What a word means to the fallback parser: V8's `KeywordTable`, matched on
1000/// the first three letters (so `January` and `Janu` are both January, and `Ja`
1001/// is nothing), with the short entries matched whole.
1002enum Keyword {
1003    Month(i64),
1004    AmPm(i64),
1005    /// A zone: its offset from UTC in hours.
1006    Zone(i64),
1007    Other,
1008}
1009
1010fn keyword(word: &str) -> Keyword {
1011    let w = word.to_ascii_lowercase();
1012    let prefix = &w[..w.len().min(3)];
1013    if w.len() >= 3 {
1014        const MONTHS: [&str; 12] = [
1015            "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
1016        ];
1017        if let Some(m) = MONTHS.iter().position(|m| *m == prefix) {
1018            return Keyword::Month(m as i64 + 1);
1019        }
1020    }
1021    match prefix {
1022        "am" if w.len() == 2 => Keyword::AmPm(0),
1023        "pm" if w.len() == 2 => Keyword::AmPm(12),
1024        "ut" if w.len() == 2 => Keyword::Zone(0),
1025        "z" => Keyword::Zone(0),
1026        "utc" | "gmt" if w.len() >= 3 => Keyword::Zone(0),
1027        "cdt" => Keyword::Zone(-5),
1028        "cst" => Keyword::Zone(-6),
1029        "edt" => Keyword::Zone(-4),
1030        "est" => Keyword::Zone(-5),
1031        "mdt" => Keyword::Zone(-6),
1032        "mst" => Keyword::Zone(-7),
1033        "pdt" => Keyword::Zone(-7),
1034        "pst" => Keyword::Zone(-8),
1035        _ => Keyword::Other,
1036    }
1037}
1038
1039/// The free-form fallback — V8's legacy `DateParser` loop, which is what makes
1040/// `new Date("March 7, 2024 10:00")`, `"1/5/2024"`, `"Oct 21, 2015 7:28 PM"`
1041/// and the `toString` form `"Thu Mar 07 2024 10:00:00 GMT-0500 (…)"` dates.
1042/// Only the IMF-fixdate header form was read before, so every one of those was
1043/// an Invalid Date.
1044///
1045/// Numbers fill the date (`DayComposer`), a number followed by `:` starts the
1046/// time (`TimeComposer`), and a zone word or a sign after the time sets the
1047/// offset (`TimeZoneComposer`). With no zone the result is LOCAL time.
1048fn parse_legacy(s: &str) -> Option<f64> {
1049    const NONE: i64 = i64::MIN;
1050    let mut t = Toks { s, i: 0 };
1051    let (mut day, mut named_month) = (Vec::with_capacity(3), NONE);
1052    let (mut time, mut hour_offset) = (Vec::with_capacity(4), NONE);
1053    let (mut sign, mut tz_hour, mut tz_min) = (0i64, NONE, NONE);
1054    let mut read_number = false;
1055    // `TimeComposer::IsExpecting`: the next field the time can take.
1056    let expecting = |time: &Vec<i64>, n: i64| match time.len() {
1057        1 | 2 => (0..60).contains(&n),
1058        3 => (0..1000).contains(&n),
1059        _ => false,
1060    };
1061    loop {
1062        match t.next() {
1063            Tok::End => break,
1064            Tok::Num(n, _) => {
1065                read_number = true;
1066                if t.skip(b':') {
1067                    if t.skip(b':') {
1068                        if !time.is_empty() {
1069                            return None;
1070                        }
1071                        time.extend([n, 0]);
1072                    } else {
1073                        if time.len() >= 4 {
1074                            return None;
1075                        }
1076                        time.push(n);
1077                        t.skip(b'.');
1078                    }
1079                } else if t.peek() == Tok::Sym(b'.') && expecting(&time, n) {
1080                    t.next();
1081                    time.push(n);
1082                    let Tok::Num(ms, len) = t.next() else {
1083                        return None;
1084                    };
1085                    // Milliseconds are the first three digits, scaled.
1086                    let ms = match len {
1087                        1 => ms * 100,
1088                        2 => ms * 10,
1089                        3 => ms,
1090                        _ => t.s[t.i - len..t.i - len + 3].parse().ok()?,
1091                    };
1092                    time.push(ms);
1093                    time.resize(4, 0);
1094                } else if tz_hour != NONE && tz_min == NONE && (0..60).contains(&n) {
1095                    tz_min = n;
1096                } else if expecting(&time, n) {
1097                    time.push(n);
1098                    time.resize(4, 0);
1099                    // The time must end at the end, white space, `Z` or a sign.
1100                    match t.peek() {
1101                        Tok::End | Tok::Space | Tok::Sym(b'+' | b'-') => {}
1102                        Tok::Word(w) if w.eq_ignore_ascii_case("z") => {}
1103                        _ => return None,
1104                    }
1105                } else {
1106                    if day.len() >= 3 {
1107                        return None;
1108                    }
1109                    day.push(n);
1110                    t.skip(b'-');
1111                }
1112            }
1113            Tok::Word(w) => match keyword(w) {
1114                Keyword::AmPm(off) if !time.is_empty() => hour_offset = off,
1115                Keyword::Month(m) => {
1116                    named_month = m;
1117                    t.skip(b'-');
1118                }
1119                Keyword::Zone(h) if read_number => {
1120                    sign = if h < 0 { -1 } else { 1 };
1121                    tz_hour = h.abs();
1122                    tz_min = 0;
1123                }
1124                _ => {
1125                    // A stray word is refused once a number has been read,
1126                    // and must be kept apart from the first number.
1127                    if read_number || matches!(t.peek(), Tok::Num(..)) {
1128                        return None;
1129                    }
1130                }
1131            },
1132            Tok::Sym(c @ (b'+' | b'-'))
1133                if (sign != 0 && tz_hour == 0 && tz_min == 0) || !time.is_empty() =>
1134            {
1135                // An offset, only after a UTC word or a time: `+05`, `+0530`,
1136                // `+05:30`.
1137                sign = if c == b'-' { -1 } else { 1 };
1138                let (n, len) = match t.peek() {
1139                    Tok::Num(n, len) => {
1140                        t.next();
1141                        (n, len)
1142                    }
1143                    _ => (0, 0),
1144                };
1145                read_number = true;
1146                if t.peek() == Tok::Sym(b':') {
1147                    tz_hour = n;
1148                    tz_min = NONE;
1149                } else if len <= 2 {
1150                    tz_hour = n;
1151                    tz_min = 0;
1152                } else if len <= 4 {
1153                    tz_hour = n / 100;
1154                    tz_min = n % 100;
1155                } else {
1156                    return None;
1157                }
1158            }
1159            Tok::Sym(b'+' | b'-' | b')') if read_number => return None,
1160            Tok::Sym(_) | Tok::Space => {}
1161        }
1162    }
1163
1164    // `DayComposer::Write`: the missing components are 1, and which one is the
1165    // year is decided by whether the first can be a day at all.
1166    if day.is_empty() {
1167        return None;
1168    }
1169    day.resize(3, 1);
1170    let is_day = |n: i64| (1..=31).contains(&n);
1171    let (mut year, month, dd) = if named_month == NONE {
1172        if is_day(day[0]) {
1173            (day[2], day[0], day[1])
1174        } else {
1175            (day[0], day[1], day[2])
1176        }
1177    } else if !is_day(day[0]) {
1178        (day[0], named_month, day[1])
1179    } else {
1180        (day[1], named_month, day[0])
1181    };
1182    if (0..=49).contains(&year) {
1183        year += 2000;
1184    } else if (50..=99).contains(&year) {
1185        year += 1900;
1186    }
1187    if !(1..=12).contains(&month) || !is_day(dd) {
1188        return None;
1189    }
1190
1191    // `TimeComposer::Write`: missing fields are 0; AM/PM needs an hour of
1192    // 0-12; hour 24 only as the very end of a day.
1193    time.resize(4, 0);
1194    let (mut h, mi, sec, ms) = (time[0], time[1], time[2], time[3]);
1195    if hour_offset != NONE {
1196        if !(0..=12).contains(&h) {
1197            return None;
1198        }
1199        h = h % 12 + hour_offset;
1200    }
1201    let in_range = (0..24).contains(&h)
1202        && (0..60).contains(&mi)
1203        && (0..60).contains(&sec)
1204        && (0..1000).contains(&ms);
1205    if !in_range && (h, mi, sec, ms) != (24, 0, 0, 0) {
1206        return None;
1207    }
1208
1209    let wall = utc_from_fields(
1210        year as f64,
1211        (month - 1) as f64,
1212        dd as f64,
1213        h as f64,
1214        mi as f64,
1215        sec as f64,
1216        ms as f64,
1217    );
1218    if sign == 0 {
1219        return Some(utc_from_local(wall));
1220    }
1221    let tz_min = if tz_min == NONE { 0 } else { tz_min };
1222    let tz_hour = if tz_hour == NONE { 0 } else { tz_hour };
1223    Some(wall - sign as f64 * (tz_hour * 3_600_000 + tz_min * 60_000) as f64)
1224}
1225
1226/// A Date's `util.inspect` rendering, resolved against an ALREADY-BORROWED host.
1227///
1228/// Node prints a Date as its ISO-8601 form — `console.log(new Date(1))` is
1229/// `1970-01-01T00:00:00.001Z`, not an object literal — and prints the string
1230/// `Invalid Date` for a NaN time value. Without this the inspect walk reached a
1231/// Date through the generic object branch, found its time value in the internal
1232/// `@@ms` slot rather than in an enumerable property, and rendered every Date
1233/// ever logged as `{}`.
1234///
1235/// Takes `&JsHost` rather than calling `with_host` because the inspect walk is
1236/// already inside that borrow; borrowing again aborts the process.
1237pub(crate) fn inspect_with_host(h: &crate::host::JsHost, v: &Value) -> String {
1238    let ms = match h.get(v) {
1239        Some(JsObj::Object(p)) => p.get("@@ms").map(|x| h.to_number(x)).unwrap_or(f64::NAN),
1240        _ => f64::NAN,
1241    };
1242    if ms.is_nan() {
1243        "Invalid Date".into()
1244    } else {
1245        iso_string(ms)
1246    }
1247}