1use chrono::{DateTime, Datelike, Timelike, Utc};
2use std::{error::Error, time::SystemTime};
3
4use super::*;
5
6#[derive(Debug, Default, Clone)]
7pub struct Date {
8 pub mod_year: i16,
9 pub mod_month: i16,
10 pub mod_day: i16,
11 pub mod_hour: i16,
12 pub mod_minute: i16,
13 pub mod_second: i16,
14 pub acc_year: i16,
15 pub acc_month: i16,
16 pub acc_day: i16,
17 pub acc_hour: i16,
18 pub acc_minute: i16,
19 pub acc_second: i16,
20}
21
22impl Date {
23 pub fn new() -> Self {
24 Date {
25 mod_year: i16::default(),
26 mod_month: i16::default(),
27 mod_day: i16::default(),
28 mod_hour: i16::default(),
29 mod_minute: i16::default(),
30 mod_second: i16::default(),
31 acc_year: i16::default(),
32 acc_month: i16::default(),
33 acc_day: i16::default(),
34 acc_hour: i16::default(),
35 acc_minute: i16::default(),
36 acc_second: i16::default(),
37 }
38 }
39
40 pub fn now() -> Self {
41 let now = SystemTime::now();
42 let utc: DateTime<Utc> = now.into();
43
44 let year = utc.year() as i16;
46 let month = utc.month() as i16;
47 let day = utc.day() as i16;
48
49 let hour = utc.hour() as i16;
51 let minute = utc.minute() as i16;
52 let second = utc.second() as i16;
53
54 Date {
55 mod_year: year,
56 mod_month: month,
57 mod_day: day,
58 mod_hour: hour,
59 mod_minute: minute,
60 mod_second: second,
61 acc_year: year,
62 acc_month: month,
63 acc_day: day,
64 acc_hour: hour,
65 acc_minute: minute,
66 acc_second: second,
67 }
68 }
69
70 pub fn from_i16_array(date: &[i16]) -> Result<Date, Box<dyn Error>> {
71 if date.len() < 12 {
72 return Err(Box::new(gds_err!(
73 "Can't create gds Date for data length less than 12"
74 )));
75 }
76 let mut it = date.iter();
77 Ok(Date {
78 mod_year: *it.next().unwrap(),
79 mod_month: *it.next().unwrap(),
80 mod_day: *it.next().unwrap(),
81 mod_hour: *it.next().unwrap(),
82 mod_minute: *it.next().unwrap(),
83 mod_second: *it.next().unwrap(),
84 acc_year: *it.next().unwrap(),
85 acc_month: *it.next().unwrap(),
86 acc_day: *it.next().unwrap(),
87 acc_hour: *it.next().unwrap(),
88 acc_minute: *it.next().unwrap(),
89 acc_second: *it.next().unwrap(),
90 })
91 }
92}
93
94impl GdsObject for Date {
95 fn to_gds(&self, _: f64) -> Result<Vec<u8>, Box<dyn Error>> {
96 let mut date_data = Vec::<u8>::new();
97 date_data.extend(self.mod_year.to_be_bytes());
98 date_data.extend(self.mod_month.to_be_bytes());
99 date_data.extend(self.mod_day.to_be_bytes());
100 date_data.extend(self.mod_hour.to_be_bytes());
101 date_data.extend(self.mod_minute.to_be_bytes());
102 date_data.extend(self.mod_second.to_be_bytes());
103 date_data.extend(self.acc_year.to_be_bytes());
104 date_data.extend(self.acc_month.to_be_bytes());
105 date_data.extend(self.acc_day.to_be_bytes());
106 date_data.extend(self.acc_hour.to_be_bytes());
107 date_data.extend(self.acc_minute.to_be_bytes());
108 date_data.extend(self.acc_second.to_be_bytes());
109 Ok(date_data)
110 }
111}