plabble_codec/codec/common/
plabble_date.rs1use crate::abstractions::EPOCH;
2use time::OffsetDateTime;
3
4pub fn to_timestamp(date: &OffsetDateTime) -> u32 {
18 (date.unix_timestamp() - EPOCH)
19 .try_into()
20 .expect("Failed to fit timestamp into u32")
21}
22
23pub fn from_timestamp(timestamp: u32) -> OffsetDateTime {
37 OffsetDateTime::from_unix_timestamp(timestamp as i64 + EPOCH).expect("Timestamp is not valid")
38}
39
40#[cfg(test)]
41mod test {
42 use time_macros::datetime;
43
44 #[test]
45 fn can_convert_date_to_timestamp() {
46 let d1 = datetime!(2020-01-01 00:00:00 UTC);
47 let d2 = datetime!(2020-01-01 00:01:00 UTC);
48 let d3 = datetime!(2020-01-01 01:00:00 UTC);
49 let d4 = datetime!(2023-03-21 18:41:30 UTC);
50
51 assert_eq!(super::to_timestamp(&d1), 0);
52 assert_eq!(super::to_timestamp(&d2), 60);
53 assert_eq!(super::to_timestamp(&d3), 3600);
54 assert_eq!(super::to_timestamp(&d4), 101587290);
55 }
56
57 #[test]
58 fn can_convert_timestamp_to_date() {
59 let d1 = datetime!(2020-01-01 00:00:00 UTC);
60 let d2 = datetime!(2020-01-01 00:01:00 UTC);
61 let d3 = datetime!(2020-01-01 01:00:00 UTC);
62 let d4 = datetime!(2023-03-21 18:41:30 UTC);
63
64 assert_eq!(super::from_timestamp(0), d1);
65 assert_eq!(super::from_timestamp(60), d2);
66 assert_eq!(super::from_timestamp(3600), d3);
67 assert_eq!(super::from_timestamp(101587290), d4);
68 }
69}