Skip to main content

siglus_scene_vm/
platform_time.rs

1//! Cross-platform time helpers.
2//!
3//! wasm32-unknown-unknown does not support std::time::Instant::now() or
4//! std::time::SystemTime::now(). Use this module anywhere runtime code needs
5//! wall-clock or monotonic time.
6
7pub use std::time::Duration;
8
9#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
10pub use web_time::Instant;
11
12#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
13pub use std::time::Instant;
14
15#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
16pub fn unix_time_millis() -> u128 {
17    let ms = js_sys::Date::now();
18    if ms.is_finite() && ms > 0.0 {
19        ms as u128
20    } else {
21        0
22    }
23}
24
25#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
26pub fn unix_time_millis() -> u128 {
27    std::time::SystemTime::now()
28        .duration_since(std::time::UNIX_EPOCH)
29        .unwrap_or_default()
30        .as_millis()
31}
32
33pub fn unix_time_secs() -> u64 {
34    (unix_time_millis() / 1000) as u64
35}
36
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38pub struct LocalTimeFields {
39    pub year: i32,
40    pub month: u32,
41    pub day: u32,
42    /// 0 = Sunday, 6 = Saturday, matching Windows SYSTEMTIME.wDayOfWeek.
43    pub weekday_sunday0: u32,
44    pub hour: u32,
45    pub minute: u32,
46    pub second: u32,
47    pub millisecond: u32,
48}
49
50#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
51pub fn local_time_fields() -> LocalTimeFields {
52    let now = js_sys::Date::new_0();
53    LocalTimeFields {
54        year: now.get_full_year() as i32,
55        month: now.get_month() + 1,
56        day: now.get_date(),
57        weekday_sunday0: now.get_day(),
58        hour: now.get_hours(),
59        minute: now.get_minutes(),
60        second: now.get_seconds(),
61        millisecond: now.get_milliseconds(),
62    }
63}
64
65#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
66pub fn local_time_fields() -> LocalTimeFields {
67    use chrono::{Datelike, Timelike};
68
69    let now = chrono::Local::now();
70    LocalTimeFields {
71        year: now.year(),
72        month: now.month(),
73        day: now.day(),
74        weekday_sunday0: now.weekday().num_days_from_sunday(),
75        hour: now.hour(),
76        minute: now.minute(),
77        second: now.second(),
78        millisecond: now.timestamp_subsec_millis(),
79    }
80}
81
82pub fn local_log_timestamp() -> String {
83    let t = local_time_fields();
84    format!(
85        "[{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}]",
86        year = t.year,
87        month = t.month,
88        day = t.day,
89        hour = t.hour,
90        minute = t.minute,
91        second = t.second,
92    )
93}
94