rsiot/message/
timestamp.rs1use serde::{Deserialize, Serialize};
2use time::{
3 OffsetDateTime, Weekday,
4 format_description::{self, well_known::Rfc3339},
5};
6
7#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
9pub struct Timestamp(OffsetDateTime);
10
11impl Timestamp {
12 pub fn format(&self, fmt: &str) -> Result<String, String> {
14 let format = format_description::parse(fmt).map_err(|e| e.to_string())?;
15 self.0.format(&format).map_err(|e| e.to_string())
16 }
17
18 pub fn to_rfc3339(&self) -> Result<String, String> {
20 self.0.format(&Rfc3339).map_err(|e| e.to_string())
21 }
22
23 pub fn unix_timestamp_nanos(&self) -> i128 {
25 self.0.unix_timestamp_nanos()
26 }
27
28 pub fn weekday(&self) -> u8 {
30 match self.0.weekday() {
31 Weekday::Monday => 1,
32 Weekday::Tuesday => 2,
33 Weekday::Wednesday => 3,
34 Weekday::Thursday => 4,
35 Weekday::Friday => 5,
36 Weekday::Saturday => 6,
37 Weekday::Sunday => 7,
38 }
39 }
40
41 pub fn hour(&self) -> u8 {
43 self.0.hour()
44 }
45
46 pub fn minute(&self) -> u8 {
48 self.0.minute()
49 }
50
51 pub fn second(&self) -> u8 {
53 self.0.second()
54 }
55}
56
57impl Default for Timestamp {
58 fn default() -> Self {
59 let local_time = OffsetDateTime::now_local();
60 let local_time = match local_time {
61 Ok(v) => v,
62 Err(_) => OffsetDateTime::now_utc(),
63 };
64 Self(local_time)
65 }
66}
67
68impl PartialOrd for Timestamp {
69 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
70 self.0.partial_cmp(&other.0)
71 }
72}