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
36/// The trait helping convert to a [`UtcDateTime`].
37pub trait ToUtcDateTime {
38    /// Converts to a [`UtcDateTime`].
39    fn to_utc_datetime(self) -> Option<UtcDateTime>;
40}
41
42impl ToUtcDateTime for i64 {
43    /// Converts a UNIX timestamp to a [`UtcDateTime`].
44    fn to_utc_datetime(self) -> Option<UtcDateTime> {
45        UtcDateTime::from_unix_timestamp(self).ok()
46    }
47}
48
49impl ToUtcDateTime for Time {
50    /// Converts a system time to a [`UtcDateTime`].
51    fn to_utc_datetime(self) -> Option<UtcDateTime> {
52        Some(UtcDateTime::from(self))
53    }
54}
55
56/// Converts a [`UtcDateTime`] to typst's datetime.
57#[cfg(feature = "typst")]
58pub fn to_typst_time(timestamp: UtcDateTime) -> typst::foundations::Datetime {
59    let datetime = ::time::PrimitiveDateTime::new(timestamp.date(), timestamp.time());
60    typst::foundations::Datetime::Datetime(datetime)
61}