Skip to main content

djs_formatters/
timestamp.rs

1//! Timestamps shown in each reader's time zone and language: [`time`].
2//!
3//! See Discord's [timestamp styles](https://docs.discord.com/developers/reference#message-formatting-timestamp-styles).
4
5use core::fmt;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8use djs_model::util::Timestamp;
9
10/// How Discord shows a [`time`]; the examples are for 20 April 2021, 16:20:30, in an English
11/// client.
12///
13/// discord.js counterpart: `TimestampStyles` (whose deprecated aliases `LongTime`,
14/// `ShortDateTime` and `LongDateTime` are [`MediumTime`](Self::MediumTime),
15/// [`LongDateShortTime`](Self::LongDateShortTime) and
16/// [`FullDateShortTime`](Self::FullDateShortTime)).
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum TimestampStyle {
20    /// `t`: 16:20.
21    ShortTime,
22    /// `T`: 16:20:30.
23    MediumTime,
24    /// `d`: 20/04/2021.
25    ShortDate,
26    /// `D`: April 20, 2021.
27    LongDate,
28    /// `f`: April 20, 2021 at 16:20 — what Discord shows without a style.
29    LongDateShortTime,
30    /// `F`: Tuesday, April 20, 2021 at 16:20.
31    FullDateShortTime,
32    /// `s`: 20/04/2021, 16:20.
33    ShortDateShortTime,
34    /// `S`: 20/04/2021, 16:20:30.
35    ShortDateMediumTime,
36    /// `R`: 4 years ago — kept up to date by the client.
37    RelativeTime,
38}
39
40impl TimestampStyle {
41    /// The style's letter, such as `R`.
42    ///
43    /// discord.js counterpart: the values of `TimestampStyles` (`@discordjs/formatters`).
44    #[must_use]
45    pub const fn as_char(self) -> char {
46        match self {
47            Self::ShortTime => 't',
48            Self::MediumTime => 'T',
49            Self::ShortDate => 'd',
50            Self::LongDate => 'D',
51            Self::LongDateShortTime => 'f',
52            Self::FullDateShortTime => 'F',
53            Self::ShortDateShortTime => 's',
54            Self::ShortDateMediumTime => 'S',
55            Self::RelativeTime => 'R',
56        }
57    }
58}
59
60/// A point in time that [`time`] can show: seconds since the Unix epoch.
61///
62/// Implemented for `i64` (seconds), [`Timestamp`] and [`SystemTime`]; implement it for a
63/// time type of another crate to pass it directly.
64///
65/// discord.js counterpart: none (`time` takes a `Date` or seconds).
66pub trait UnixSeconds {
67    /// Whole seconds since 1970-01-01 00:00:00 UTC, rounded down (negative before it).
68    fn unix_seconds(&self) -> i64;
69}
70
71impl UnixSeconds for i64 {
72    fn unix_seconds(&self) -> i64 {
73        *self
74    }
75}
76
77impl UnixSeconds for Timestamp {
78    fn unix_seconds(&self) -> i64 {
79        self.as_unix_secs()
80    }
81}
82
83impl UnixSeconds for SystemTime {
84    /// Saturates at `i64::MIN` / `i64::MAX` for times billions of years away.
85    fn unix_seconds(&self) -> i64 {
86        match self.duration_since(UNIX_EPOCH) {
87            Ok(after) => i64::try_from(after.as_secs()).unwrap_or(i64::MAX),
88            Err(before) => {
89                let before = before.duration();
90                // Round down: 0.5 s before the epoch is second -1.
91                let seconds = before.as_secs() + u64::from(before.subsec_nanos() > 0);
92                i64::try_from(seconds).map_or(i64::MIN, |seconds| -seconds)
93            }
94        }
95    }
96}
97
98impl<T: UnixSeconds + ?Sized> UnixSeconds for &T {
99    fn unix_seconds(&self) -> i64 {
100        (**self).unix_seconds()
101    }
102}
103
104/// A timestamp: `<t:SECONDS>` or `<t:SECONDS:STYLE>`. Returned by [`time`].
105///
106/// discord.js counterpart: the string `time` returns, with `TimestampStyles` (`@discordjs/formatters`).
107#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
108#[must_use = "a formatter does nothing until it is written"]
109pub struct Time {
110    seconds: i64,
111    style: Option<TimestampStyle>,
112}
113
114/// Shows `at` in each reader's time zone and language: `<t:1618953630>`.
115///
116/// Without a [`style`](Time::style) Discord uses
117/// [`LongDateShortTime`](TimestampStyle::LongDateShortTime) (D-213). Discord counts whole
118/// seconds, so a fraction is dropped (rounding down).
119///
120/// discord.js counterpart: `time`.
121///
122/// # Examples
123///
124/// ```
125/// use djs_formatters::{TimestampStyle, time};
126/// use djs_model::util::Timestamp;
127///
128/// assert_eq!(time(1_618_953_630).to_string(), "<t:1618953630>");
129/// assert_eq!(time(1_618_953_630).style(TimestampStyle::RelativeTime).to_string(), "<t:1618953630:R>");
130///
131/// let sent = Timestamp::parse("2021-04-20T21:20:30.250+00:00").unwrap();
132/// assert_eq!(time(sent).style(TimestampStyle::ShortDate).to_string(), "<t:1618953630:d>");
133///
134/// // Now, as "in a few seconds" / "a few seconds ago":
135/// let now = time(std::time::SystemTime::now()).style(TimestampStyle::RelativeTime);
136/// # let _ = now;
137/// ```
138pub fn time(at: impl UnixSeconds) -> Time {
139    Time {
140        seconds: at.unix_seconds(),
141        style: None,
142    }
143}
144
145impl Time {
146    /// Sets how the time is shown.
147    ///
148    /// discord.js counterpart: the `style` argument of `time` (`@discordjs/formatters`).
149    pub const fn style(mut self, style: TimestampStyle) -> Self {
150        self.style = Some(style);
151        self
152    }
153
154    /// The seconds since the Unix epoch this timestamp shows.
155    ///
156    /// discord.js counterpart: the `seconds` argument of `time` (`@discordjs/formatters`).
157    #[must_use]
158    pub const fn seconds(self) -> i64 {
159        self.seconds
160    }
161}
162
163impl fmt::Display for Time {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        match self.style {
166            Some(style) => write!(f, "<t:{}:{}>", self.seconds, style.as_char()),
167            None => write!(f, "<t:{}>", self.seconds),
168        }
169    }
170}