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 crate::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/// Returns the current UNIX epoch time in seconds.
23#[must_use]
24#[allow(clippy::cast_possible_truncation)]
25pub fn now_secs() -> u64 {
26    (time_nanos() / 1_000_000_000) as u64
27}
28
29/// Returns the current UNIX epoch time in milliseconds.
30#[must_use]
31#[allow(clippy::cast_possible_truncation)]
32pub fn now_millis() -> u64 {
33    (time_nanos() / 1_000_000) as u64
34}
35
36/// Returns the current UNIX epoch time in microseconds.
37#[must_use]
38#[allow(clippy::cast_possible_truncation)]
39pub fn now_micros() -> u64 {
40    (time_nanos() / 1_000) as u64
41}
42
43/// Returns the current UNIX epoch time in nanoseconds.
44#[must_use]
45#[allow(clippy::cast_possible_truncation)]
46pub fn now_nanos() -> u64 {
47    time_nanos() as u64
48}
49
50///
51/// TESTS
52///
53
54#[cfg(test)]
55pub mod test {
56    use super::*;
57
58    #[test]
59    fn test_now_secs_sanity() {
60        let now = now_secs();
61        let current_year_secs = 1_700_000_000; // ≈ Oct 2023
62        assert!(now > current_year_secs);
63    }
64}