tinymist_std/
time.rs

1//! Cross platform time utilities.
2
3pub use std::time::SystemTime as Time;
4pub use time::UtcDateTime;
5
6#[cfg(not(feature = "web"))]
7pub use std::time::{Duration, Instant};
8#[cfg(feature = "web")]
9pub use web_time::{Duration, Instant};
10
11/// Returns the current datetime in utc (UTC+0).
12pub fn utc_now() -> UtcDateTime {
13    now().into()
14}
15
16/// Returns the current system time (UTC+0).
17#[cfg(any(feature = "system", feature = "web"))]
18pub fn now() -> Time {
19    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
20    {
21        Time::now()
22    }
23    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
24    {
25        use web_time::web::SystemTimeExt;
26        web_time::SystemTime::now().to_std()
27    }
28}
29
30/// Returns a dummy time on environments that do not support time.
31#[cfg(not(any(feature = "system", feature = "web")))]
32pub fn now() -> Time {
33    Time::UNIX_EPOCH
34}
35
36pub use time::format_description::well_known::Rfc3339;
37
38/// The trait helping convert to a [`UtcDateTime`].
39pub trait ToUtcDateTime {
40    /// Converts to a [`UtcDateTime`].
41    fn to_utc_datetime(self) -> Option<UtcDateTime>;
42}
43
44impl ToUtcDateTime for i64 {
45    /// Converts a UNIX timestamp to a [`UtcDateTime`].
46    fn to_utc_datetime(self) -> Option<UtcDateTime> {
47        UtcDateTime::from_unix_timestamp(self).ok()
48    }
49}
50
51impl ToUtcDateTime for Time {
52    /// Converts a system time to a [`UtcDateTime`].
53    fn to_utc_datetime(self) -> Option<UtcDateTime> {
54        Some(UtcDateTime::from(self))
55    }
56}
57
58/// Converts a [`UtcDateTime`] to typst's datetime.
59#[cfg(feature = "typst")]
60pub fn to_typst_time(timestamp: UtcDateTime) -> typst::foundations::Datetime {
61    let datetime = ::time::PrimitiveDateTime::new(timestamp.date(), timestamp.time());
62    typst::foundations::Datetime::Datetime(datetime)
63}