use crate::abstractions::EPOCH;
use time::OffsetDateTime;
pub fn to_timestamp(date: &OffsetDateTime) -> u32 {
(date.unix_timestamp() - EPOCH)
.try_into()
.expect("Failed to fit timestamp into u32")
}
pub fn from_timestamp(timestamp: u32) -> OffsetDateTime {
OffsetDateTime::from_unix_timestamp(timestamp as i64 + EPOCH).expect("Timestamp is not valid")
}
#[cfg(test)]
mod test {
use time_macros::datetime;
#[test]
fn can_convert_date_to_timestamp() {
let d1 = datetime!(2020-01-01 00:00:00 UTC);
let d2 = datetime!(2020-01-01 00:01:00 UTC);
let d3 = datetime!(2020-01-01 01:00:00 UTC);
let d4 = datetime!(2023-03-21 18:41:30 UTC);
assert_eq!(super::to_timestamp(&d1), 0);
assert_eq!(super::to_timestamp(&d2), 60);
assert_eq!(super::to_timestamp(&d3), 3600);
assert_eq!(super::to_timestamp(&d4), 101587290);
}
#[test]
fn can_convert_timestamp_to_date() {
let d1 = datetime!(2020-01-01 00:00:00 UTC);
let d2 = datetime!(2020-01-01 00:01:00 UTC);
let d3 = datetime!(2020-01-01 01:00:00 UTC);
let d4 = datetime!(2023-03-21 18:41:30 UTC);
assert_eq!(super::from_timestamp(0), d1);
assert_eq!(super::from_timestamp(60), d2);
assert_eq!(super::from_timestamp(3600), d3);
assert_eq!(super::from_timestamp(101587290), d4);
}
}