Skip to main content

canic_core/cdk/utils/
time.rs

1//! Module: cdk::utils::time
2//!
3//! Responsibility: timestamp helpers that work under host and IC execution.
4//! Does not own: timer scheduling, lifecycle hooks, or clock policy.
5//! Boundary: exposes UNIX epoch timestamps at common precisions.
6
7use std::time::SystemTime;
8
9/// Return the current UNIX epoch time in nanoseconds as the internal base unit.
10#[cfg_attr(target_arch = "wasm32", expect(unreachable_code))]
11fn time_nanos() -> u128 {
12    #[cfg(target_arch = "wasm32")]
13    {
14        return u128::from(crate::cdk::api::time());
15    }
16
17    match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
18        Ok(d) => d.as_nanos(),
19        Err(_) => 0,
20    }
21}
22
23/// Returns the current UNIX epoch time in seconds.
24#[must_use]
25#[expect(clippy::cast_possible_truncation)]
26pub fn now_secs() -> u64 {
27    (time_nanos() / 1_000_000_000) as u64
28}
29
30/// Returns the current UNIX epoch time in milliseconds.
31#[must_use]
32#[expect(clippy::cast_possible_truncation)]
33pub fn now_millis() -> u64 {
34    (time_nanos() / 1_000_000) as u64
35}
36
37/// Returns the current UNIX epoch time in microseconds.
38#[must_use]
39#[expect(clippy::cast_possible_truncation)]
40pub fn now_micros() -> u64 {
41    (time_nanos() / 1_000) as u64
42}
43
44/// Returns the current UNIX epoch time in nanoseconds.
45#[must_use]
46#[expect(clippy::cast_possible_truncation)]
47pub fn now_nanos() -> u64 {
48    time_nanos() as u64
49}
50
51// -----------------------------------------------------------------------------
52// Tests
53// -----------------------------------------------------------------------------
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn test_now_secs_sanity() {
61        let now = now_secs();
62        let current_year_secs = 1_700_000_000; // roughly Oct 2023
63        assert!(now > current_year_secs);
64    }
65}