1
//! Local wall-clock text to UTC instants, with the zone given as a function so
2
//! the repeated and missing hours of a DST change can be tested.
3

            
4
const MS_PER_MINUTE: i64 = 60_000;
5
const MS_PER_DAY: i64 = 86_400_000;
6

            
7
/// Days since 1970-01-01 of a proleptic Gregorian date.
8
166
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
9
166
    let y = if month <= 2 { year - 1 } else { year };
10
166
    let era = y.div_euclid(400);
11
166
    let yoe = y.rem_euclid(400);
12
166
    let mp = (month + 9) % 12;
13
166
    let doy = (153 * mp + 2) / 5 + day - 1;
14
166
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
15
166
    era * 146_097 + doe - 719_468
16
166
}
17

            
18
101
fn civil_from_days(days: i64) -> (i64, i64, i64) {
19
101
    let z = days + 719_468;
20
101
    let era = z.div_euclid(146_097);
21
101
    let doe = z.rem_euclid(146_097);
22
101
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
23
101
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
24
101
    let mp = (5 * doy + 2) / 153;
25
101
    let day = doy - (153 * mp + 2) / 5 + 1;
26
101
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
27
101
    let year = yoe + era * 400 + i64::from(month <= 2);
28
101
    (year, month, day)
29
101
}
30

            
31
445
fn number(text: &str, digits: usize) -> Option<i64> {
32
1063
    (text.len() == digits && text.bytes().all(|b| b.is_ascii_digit()))
33
442
        .then(|| text.parse().ok())
34
        .flatten()
35
445
}
36

            
37
86
fn valid_day(year: i64, month: i64, day: i64) -> bool {
38
86
    (1..=12).contains(&month)
39
85
        && day >= 1
40
85
        && civil_from_days(days_from_civil(year, month, day)) == (year, month, day)
41
86
}
42

            
43
/// Parses `YYYY-MM-DDTHH:MM[:SS]` as a wall-clock time, in ms as if it were UTC.
44
#[must_use]
45
92
pub fn parse_local(text: &str) -> Option<i64> {
46
92
    let (date, time) = text.split_once('T')?;
47
90
    let mut d = date.splitn(3, '-');
48
    let (year, month, day) = (
49
90
        number(d.next()?, 4)?,
50
89
        number(d.next()?, 2)?,
51
88
        number(d.next()?, 2)?,
52
    );
53
88
    let mut t = time.splitn(3, ':');
54
88
    let hour = number(t.next()?, 2)?;
55
88
    let minute = number(t.next()?, 2)?;
56
87
    let second = t.next().map_or(Some(0), |s| number(s, 2))?;
57
86
    (valid_day(year, month, day) && hour < 24 && minute < 60 && second < 60).then(|| {
58
81
        days_from_civil(year, month, day) * MS_PER_DAY + ((hour * 60 + minute) * 60 + second) * 1000
59
81
    })
60
92
}
61

            
62
/// The wall-clock text `YYYY-MM-DDTHH:MM` of an instant in a zone `offset_minutes` east of UTC.
63
#[must_use]
64
5
pub fn format_local(utc_ms: i64, offset_minutes: i32) -> String {
65
5
    let local = utc_ms + i64::from(offset_minutes) * MS_PER_MINUTE;
66
5
    let (year, month, day) = civil_from_days(local.div_euclid(MS_PER_DAY));
67
5
    let minutes = local.rem_euclid(MS_PER_DAY) / MS_PER_MINUTE;
68
5
    format!(
69
5
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}",
70
5
        minutes / 60,
71
5
        minutes % 60
72
    )
73
5
}
74

            
75
/// `toISOString`-style UTC text of an instant.
76
#[must_use]
77
11
pub fn format_utc(utc_ms: i64) -> String {
78
11
    let (year, month, day) = civil_from_days(utc_ms.div_euclid(MS_PER_DAY));
79
11
    let in_day = utc_ms.rem_euclid(MS_PER_DAY);
80
11
    format!(
81
11
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
82
11
        in_day / 3_600_000,
83
11
        in_day / MS_PER_MINUTE % 60,
84
11
        in_day / 1000 % 60,
85
11
        in_day % 1000
86
    )
87
11
}
88

            
89
/// The instant of a wall-clock time. `offset_at(utc_ms)` is the zone offset in
90
/// minutes east of UTC at that instant. A repeated hour resolves to its first
91
/// occurrence and a missing hour is read with the offset before the change,
92
/// as `new Date(text)` does.
93
9
pub fn local_to_utc(wall_ms: i64, offset_at: impl Fn(i64) -> i32) -> i64 {
94
9
    let before = offset_at(wall_ms - MS_PER_DAY);
95
9
    let after = offset_at(wall_ms + MS_PER_DAY);
96
18
    let candidates = [before, after].map(|o| wall_ms - i64::from(o) * MS_PER_MINUTE);
97
9
    let consistent = candidates
98
9
        .iter()
99
9
        .zip([before, after])
100
18
        .filter_map(|(utc, o)| (offset_at(*utc) == o).then_some(*utc));
101
9
    consistent
102
9
        .min()
103
9
        .unwrap_or(wall_ms - i64::from(before) * MS_PER_MINUTE)
104
9
}
105

            
106
#[cfg(test)]
107
#[path = "date_zone_tests.rs"]
108
mod tests;