Skip to main content

djs_model/util/
timestamp.rs

1//! ISO 8601 timestamps as used by the Discord API.
2
3use core::{fmt, str::FromStr};
4// `std::time` has no clock on `wasm32-unknown-unknown`; `web-time` reads the JS host's (D-397).
5#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
6use std::time::{SystemTime, UNIX_EPOCH};
7
8#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
9use web_time::{SystemTime, UNIX_EPOCH};
10
11use serde::{
12    Deserialize, Deserializer, Serialize, Serializer,
13    de::{Error as DeError, Visitor},
14};
15
16/// A point in time, as sent by Discord in ISO 8601 format.
17///
18/// Discord timestamps look like `2026-11-10T19:42:07.123000+00:00`. They are stored here as a
19/// single `i64` of **microseconds since the Unix epoch** (8 bytes, `Copy`), which is the
20/// precision Discord uses. Parsing and formatting are implemented without any date/time
21/// dependency.
22///
23/// Timestamps are ordered chronologically.
24///
25/// discord.js counterpart: none (discord.js turns timestamps into `Date`s).
26///
27/// # Examples
28///
29/// ```
30/// use djs_model::util::Timestamp;
31///
32/// let ts: Timestamp = "2021-01-01T12:30:00.5+00:00".parse().unwrap();
33/// assert_eq!(ts.as_unix_millis(), 1_609_504_200_500);
34/// assert_eq!(ts.to_string(), "2021-01-01T12:30:00.500000+00:00");
35///
36/// // Offsets are normalised to UTC.
37/// let same: Timestamp = "2021-01-01T14:30:00.500+02:00".parse().unwrap();
38/// assert_eq!(ts, same);
39/// ```
40#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
41pub struct Timestamp {
42    unix_micros: i64,
43}
44
45const MICROS_PER_SECOND: i64 = 1_000_000;
46const SECONDS_PER_DAY: i64 = 86_400;
47
48impl Timestamp {
49    /// Creates a timestamp from microseconds since the Unix epoch.
50    ///
51    /// discord.js counterpart: `new Date(ms)`.
52    #[must_use]
53    pub const fn from_unix_micros(unix_micros: i64) -> Self {
54        Self { unix_micros }
55    }
56
57    /// Creates a timestamp from milliseconds since the Unix epoch.
58    ///
59    /// Returns `None` if the value overflows the microsecond representation.
60    ///
61    /// discord.js counterpart: `new Date(ms)`.
62    #[must_use]
63    pub const fn from_unix_millis(unix_millis: i64) -> Option<Self> {
64        match unix_millis.checked_mul(1_000) {
65            Some(unix_micros) => Some(Self { unix_micros }),
66            None => None,
67        }
68    }
69
70    /// Creates a timestamp from seconds since the Unix epoch.
71    ///
72    /// Returns `None` if the value overflows the microsecond representation.
73    ///
74    /// discord.js counterpart: `new Date(seconds * 1000)`.
75    #[must_use]
76    pub const fn from_unix_secs(unix_secs: i64) -> Option<Self> {
77        match unix_secs.checked_mul(MICROS_PER_SECOND) {
78            Some(unix_micros) => Some(Self { unix_micros }),
79            None => None,
80        }
81    }
82
83    /// Returns the current system time.
84    ///
85    /// discord.js counterpart: `Date.now()`.
86    ///
87    /// # Panics
88    ///
89    /// Panics if the system clock is set before 1970 or after the year 294 247.
90    #[must_use]
91    pub fn now() -> Self {
92        let since_epoch = SystemTime::now()
93            .duration_since(UNIX_EPOCH)
94            .expect("system clock is set before the Unix epoch");
95        Self {
96            unix_micros: i64::try_from(since_epoch.as_micros())
97                .expect("system clock is too far in the future"),
98        }
99    }
100
101    /// Returns the number of microseconds since the Unix epoch.
102    ///
103    /// discord.js counterpart: `Date#getTime`.
104    #[must_use]
105    pub const fn as_unix_micros(self) -> i64 {
106        self.unix_micros
107    }
108
109    /// Returns the number of whole milliseconds since the Unix epoch (rounded towards negative
110    /// infinity).
111    ///
112    /// discord.js counterpart: `Date#getTime`.
113    #[must_use]
114    pub const fn as_unix_millis(self) -> i64 {
115        self.unix_micros.div_euclid(1_000)
116    }
117
118    /// Returns the number of whole seconds since the Unix epoch (rounded towards negative
119    /// infinity).
120    ///
121    /// This is the value expected by Discord's `<t:…>` timestamp markdown.
122    ///
123    /// discord.js counterpart: `Date#getTime`.
124    #[must_use]
125    pub const fn as_unix_secs(self) -> i64 {
126        self.unix_micros.div_euclid(MICROS_PER_SECOND)
127    }
128
129    /// Parses an ISO 8601 / RFC 3339 timestamp such as `2026-11-10T19:42:07.123000+00:00`.
130    ///
131    /// Accepted format: `YYYY-MM-DDTHH:MM:SS`, an optional fraction of 1–9 digits (digits
132    /// beyond microseconds are truncated), and a `Z` or `±HH:MM` offset. A space is accepted in
133    /// place of `T`.
134    ///
135    /// discord.js counterpart: `new Date(string)`, as discord.js parses timestamps.
136    ///
137    /// # Errors
138    ///
139    /// Returns [`ParseTimestampError`] if the input is not in that format or contains an
140    /// out-of-range component (for example month `13` or `February 30`).
141    pub fn parse(input: &str) -> Result<Self, ParseTimestampError> {
142        parse(input.as_bytes(), false).ok_or(ParseTimestampError(()))
143    }
144
145    /// Like [`parse`](Self::parse), but a missing offset means UTC (webhook event bodies send
146    /// times without one).
147    pub(crate) fn parse_assume_utc(input: &str) -> Result<Self, ParseTimestampError> {
148        parse(input.as_bytes(), true).ok_or(ParseTimestampError(()))
149    }
150}
151
152impl FromStr for Timestamp {
153    type Err = ParseTimestampError;
154
155    fn from_str(s: &str) -> Result<Self, Self::Err> {
156        Self::parse(s)
157    }
158}
159
160/// Formats as `YYYY-MM-DDTHH:MM:SS.ffffff+00:00`, the format Discord itself uses.
161impl fmt::Display for Timestamp {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        let days = self
164            .unix_micros
165            .div_euclid(SECONDS_PER_DAY * MICROS_PER_SECOND);
166        let micros_of_day = self
167            .unix_micros
168            .rem_euclid(SECONDS_PER_DAY * MICROS_PER_SECOND);
169        let (year, month, day) = civil_from_days(days);
170        let seconds_of_day = micros_of_day / MICROS_PER_SECOND;
171        let micros = micros_of_day % MICROS_PER_SECOND;
172        write!(
173            f,
174            "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{micros:06}+00:00",
175            seconds_of_day / 3_600,
176            seconds_of_day / 60 % 60,
177            seconds_of_day % 60,
178        )
179    }
180}
181
182/// The error returned when parsing a [`Timestamp`] fails.
183///
184/// discord.js counterpart: none (discord.js turns timestamps into `Date`s).
185#[derive(Clone, Debug, PartialEq, Eq)]
186pub struct ParseTimestampError(());
187
188impl fmt::Display for ParseTimestampError {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        f.write_str("invalid ISO 8601 timestamp")
191    }
192}
193
194impl core::error::Error for ParseTimestampError {}
195
196impl Serialize for Timestamp {
197    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
198        serializer.collect_str(self)
199    }
200}
201
202impl<'de> Deserialize<'de> for Timestamp {
203    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
204        struct TimestampVisitor;
205
206        impl Visitor<'_> for TimestampVisitor {
207            type Value = Timestamp;
208
209            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210                f.write_str("an ISO 8601 timestamp string")
211            }
212
213            fn visit_str<E: DeError>(self, value: &str) -> Result<Self::Value, E> {
214                Timestamp::parse(value).map_err(E::custom)
215            }
216        }
217
218        deserializer.deserialize_str(TimestampVisitor)
219    }
220}
221
222/// Parses `len` ASCII digits starting at `at`.
223fn digits(input: &[u8], at: usize, len: usize) -> Option<i64> {
224    let slice = input.get(at..at + len)?;
225    let mut value = 0_i64;
226    for &byte in slice {
227        if !byte.is_ascii_digit() {
228            return None;
229        }
230        value = value * 10 + i64::from(byte - b'0');
231    }
232    Some(value)
233}
234
235fn expect(input: &[u8], at: usize, byte: u8) -> Option<()> {
236    (input.get(at) == Some(&byte)).then_some(())
237}
238
239fn parse(input: &[u8], assume_utc: bool) -> Option<Timestamp> {
240    // YYYY-MM-DDTHH:MM:SS
241    let year = digits(input, 0, 4)?;
242    expect(input, 4, b'-')?;
243    let month = digits(input, 5, 2)?;
244    expect(input, 7, b'-')?;
245    let day = digits(input, 8, 2)?;
246    if !matches!(input.get(10), Some(b'T' | b't' | b' ')) {
247        return None;
248    }
249    let hour = digits(input, 11, 2)?;
250    expect(input, 13, b':')?;
251    let minute = digits(input, 14, 2)?;
252    expect(input, 16, b':')?;
253    let second = digits(input, 17, 2)?;
254
255    if !(1..=12).contains(&month)
256        || day < 1
257        || day > days_in_month(year, month)
258        || hour > 23
259        || minute > 59
260        || second > 59
261    {
262        return None;
263    }
264
265    // Optional fraction: 1–9 digits, truncated to microseconds.
266    let mut at = 19;
267    let mut micros = 0_i64;
268    if input.get(at) == Some(&b'.') {
269        at += 1;
270        let start = at;
271        while let Some(byte) = input.get(at).filter(|byte| byte.is_ascii_digit()) {
272            if at - start < 6 {
273                micros = micros * 10 + i64::from(byte - b'0');
274            }
275            at += 1;
276        }
277        let len = at - start;
278        if len == 0 || len > 9 {
279            return None;
280        }
281        for _ in len..6 {
282            micros *= 10;
283        }
284    }
285
286    // Offset: `Z` or `±HH:MM` (or nothing, read as UTC, when `assume_utc`).
287    let offset_seconds = match input.get(at) {
288        None if assume_utc => 0,
289        Some(b'Z' | b'z') => {
290            at += 1;
291            0
292        }
293        Some(sign @ (b'+' | b'-')) => {
294            let offset_hour = digits(input, at + 1, 2)?;
295            expect(input, at + 3, b':')?;
296            let offset_minute = digits(input, at + 4, 2)?;
297            if offset_hour > 23 || offset_minute > 59 {
298                return None;
299            }
300            at += 6;
301            let offset = offset_hour * 3_600 + offset_minute * 60;
302            if *sign == b'+' { offset } else { -offset }
303        }
304        _ => return None,
305    };
306    if at != input.len() {
307        return None;
308    }
309
310    let days = days_from_civil(year, month, day);
311    let seconds = days * SECONDS_PER_DAY + hour * 3_600 + minute * 60 + second - offset_seconds;
312    Some(Timestamp::from_unix_micros(
313        seconds * MICROS_PER_SECOND + micros,
314    ))
315}
316
317const fn is_leap_year(year: i64) -> bool {
318    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
319}
320
321const fn days_in_month(year: i64, month: i64) -> i64 {
322    match month {
323        2 if is_leap_year(year) => 29,
324        2 => 28,
325        4 | 6 | 9 | 11 => 30,
326        _ => 31,
327    }
328}
329
330/// Days since 1970-01-01 for a proleptic Gregorian date.
331///
332/// Algorithm by Howard Hinnant, "chrono-Compatible Low-Level Date Algorithms".
333const fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
334    let year = if month <= 2 { year - 1 } else { year };
335    let era = year.div_euclid(400);
336    let year_of_era = year - era * 400;
337    let month_index = (month + 9) % 12; // March = 0
338    let day_of_year = (153 * month_index + 2) / 5 + day - 1;
339    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
340    era * 146_097 + day_of_era - 719_468
341}
342
343/// Inverse of [`days_from_civil`].
344const fn civil_from_days(days: i64) -> (i64, i64, i64) {
345    let days = days + 719_468;
346    let era = days.div_euclid(146_097);
347    let day_of_era = days - era * 146_097;
348    let year_of_era =
349        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
350    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
351    let month_index = (5 * day_of_year + 2) / 153;
352    let day = day_of_year - (153 * month_index + 2) / 5 + 1;
353    let month = if month_index < 10 {
354        month_index + 3
355    } else {
356        month_index - 9
357    };
358    let year = year_of_era + era * 400 + if month <= 2 { 1 } else { 0 };
359    (year, month, day)
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    #[test]
367    fn parse_discord_formats() {
368        let with_fraction: Timestamp = "2017-07-11T17:27:07.299000+00:00".parse().unwrap();
369        assert_eq!(with_fraction.as_unix_millis(), 1_499_794_027_299);
370
371        let without_fraction: Timestamp = "2017-07-11T17:27:07+00:00".parse().unwrap();
372        assert_eq!(without_fraction.as_unix_secs(), 1_499_794_027);
373
374        let zulu: Timestamp = "2017-07-11T17:27:07.299Z".parse().unwrap();
375        assert_eq!(zulu, with_fraction);
376    }
377
378    #[test]
379    fn nanosecond_fraction_is_truncated() {
380        let ts: Timestamp = "1970-01-01T00:00:00.123456789Z".parse().unwrap();
381        assert_eq!(ts.as_unix_micros(), 123_456);
382    }
383
384    #[test]
385    fn display_round_trip() {
386        for input in [
387            "1970-01-01T00:00:00.000000+00:00",
388            "2000-02-29T23:59:59.999999+00:00",
389            "2026-11-10T19:42:07.123000+00:00",
390            "1969-12-31T23:59:59.500000+00:00",
391        ] {
392            let ts: Timestamp = input.parse().unwrap();
393            assert_eq!(ts.to_string(), input);
394        }
395    }
396
397    #[test]
398    fn negative_offset() {
399        let ts: Timestamp = "2021-01-01T00:00:00-05:30".parse().unwrap();
400        assert_eq!(ts.to_string(), "2021-01-01T05:30:00.000000+00:00");
401    }
402
403    #[test]
404    fn missing_offset_only_with_assume_utc() {
405        let input = "2024-10-18T14:42:53.064834";
406        assert!(input.parse::<Timestamp>().is_err());
407        let ts = Timestamp::parse_assume_utc(input).unwrap();
408        assert_eq!(ts, "2024-10-18T14:42:53.064834Z".parse().unwrap());
409        // An explicit offset still applies, and junk is still rejected.
410        assert_eq!(
411            Timestamp::parse_assume_utc("2024-10-18T16:42:53.064834+02:00").unwrap(),
412            ts
413        );
414        assert!(Timestamp::parse_assume_utc("2024-10-18T14:42:53.").is_err());
415        assert!(Timestamp::parse_assume_utc("2024-10-18T14:42:53x").is_err());
416    }
417
418    #[test]
419    fn rejects_invalid() {
420        for input in [
421            "",
422            "2021-13-01T00:00:00Z",
423            "2021-02-29T00:00:00Z",
424            "2021-01-01T24:00:00Z",
425            "2021-01-01T00:00:00",
426            "2021-01-01T00:00:00.Z",
427            "2021-01-01T00:00:00.1234567890Z",
428            "2021-01-01T00:00:00+0000",
429            "2021-01-01T00:00:00Zjunk",
430            "2021-1-01T00:00:00Z",
431        ] {
432            assert!(
433                input.parse::<Timestamp>().is_err(),
434                "{input:?} should be rejected"
435            );
436        }
437    }
438
439    #[test]
440    fn civil_round_trip() {
441        for days in (-800_000..800_000).step_by(997) {
442            let (year, month, day) = civil_from_days(days);
443            assert_eq!(days_from_civil(year, month, day), days);
444        }
445    }
446}