oxidite_utils/
date.rs

1//! Date and time utilities
2
3use chrono::{DateTime, Utc, NaiveDateTime};
4
5pub use chrono::Duration;
6
7/// Get the current UTC timestamp
8pub fn now() -> DateTime<Utc> {
9    Utc::now()
10}
11
12/// Format a datetime to a string
13pub fn format_date(dt: &DateTime<Utc>, format: &str) -> String {
14    dt.format(format).to_string()
15}
16
17/// Parse a date string
18pub fn parse_date(s: &str, format: &str) -> Option<DateTime<Utc>> {
19    NaiveDateTime::parse_from_str(s, format)
20        .ok()
21        .map(|dt| dt.and_utc())
22}
23
24/// Get Unix timestamp in seconds
25pub fn unix_timestamp() -> i64 {
26    Utc::now().timestamp()
27}
28
29/// Get Unix timestamp in milliseconds
30pub fn unix_timestamp_millis() -> i64 {
31    Utc::now().timestamp_millis()
32}
33
34/// Check if a timestamp is expired
35pub fn is_expired(expires_at: i64) -> bool {
36    unix_timestamp() >= expires_at
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn test_now() {
45        let dt = now();
46        assert!(dt.timestamp() > 0);
47    }
48
49    #[test]
50    fn test_format_date() {
51        let dt = now();
52        let formatted = format_date(&dt, "%Y-%m-%d");
53        assert!(formatted.len() == 10);
54    }
55
56    #[test]
57    fn test_is_expired() {
58        let past = unix_timestamp() - 100;
59        let future = unix_timestamp() + 100;
60        
61        assert!(is_expired(past));
62        assert!(!is_expired(future));
63    }
64}