canic_utils/
time.rs

1//!
2//! Time helpers abstracting over host/IC execution so call sites can request
3//! UNIX epoch timestamps at various precisions.
4//!
5
6use std::time::SystemTime;
7
8// time_nanos
9#[allow(unreachable_code)]
10fn time_nanos() -> u128 {
11    #[cfg(target_arch = "wasm32")]
12    {
13        return ::ic_cdk::api::time() as u128;
14    }
15
16    match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
17        Ok(d) => d.as_nanos(),
18        Err(_) => 0,
19    }
20}
21
22///
23/// Returns the current UNIX epoch time in seconds.
24///
25#[must_use]
26#[allow(clippy::cast_possible_truncation)]
27pub fn now_secs() -> u64 {
28    (time_nanos() / 1_000_000_000) as u64
29}
30
31///
32/// Returns the current UNIX epoch time in milliseconds.
33///
34#[must_use]
35#[allow(clippy::cast_possible_truncation)]
36pub fn now_millis() -> u64 {
37    (time_nanos() / 1_000_000) as u64
38}
39
40///
41/// Returns the current UNIX epoch time in microseconds.
42///
43#[must_use]
44#[allow(clippy::cast_possible_truncation)]
45pub fn now_micros() -> u64 {
46    (time_nanos() / 1_000) as u64
47}
48
49///
50/// Returns the current UNIX epoch time in nanoseconds.
51///
52#[must_use]
53#[allow(clippy::cast_possible_truncation)]
54pub fn now_nanos() -> u64 {
55    time_nanos() as u64
56}
57
58///
59/// TESTS
60///
61
62#[cfg(test)]
63pub mod test {
64    use super::*;
65
66    #[test]
67    fn test_now_secs_sanity() {
68        let now = now_secs();
69        let current_year_secs = 1_700_000_000; // ≈ Oct 2023
70        assert!(now > current_year_secs);
71    }
72}