torrust_index/utils/
clock.rs

1use chrono::{DateTime, TimeDelta, Utc};
2
3pub const DATETIME_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
4
5/// Returns the current timestamp in seconds.
6///
7/// # Panics
8///
9/// This function should never panic unless the current timestamp from the
10/// time library is negative, which should never happen.
11#[must_use]
12pub fn now() -> u64 {
13    u64::try_from(chrono::prelude::Utc::now().timestamp()).expect("timestamp should be positive")
14}
15
16/// Returns the datetime some seconds ago.
17///
18/// # Panics
19///
20/// The function panics if the number of seconds passed as a parameter
21/// are more than `i64::MAX` / `1_000` or less than `-i64::MAX` / `1_000`.
22#[must_use]
23pub fn seconds_ago_utc(seconds: i64) -> DateTime<chrono::Utc> {
24    Utc::now()
25        - TimeDelta::try_seconds(seconds).expect("seconds should be more than i64::MAX / 1_000 or less than -i64::MAX / 1_000")
26}
27
28/// Returns the current time in database format.
29///
30/// For example: `2024-03-12 15:56:24`.
31#[must_use]
32pub fn datetime_now() -> String {
33    Utc::now().format(DATETIME_FORMAT).to_string()
34}