1use std::{time::{SystemTime, UNIX_EPOCH}};
2
3
4pub struct Timestamp {
7 pub timestamp_s: u64, pub timestamp_ms:u128,
9 pub timestamp_ns:u128,
10}
11
12impl Default for Timestamp {
13 fn default() -> Self {
14 Timestamp {
15 timestamp_s: 0,
16 timestamp_ms: 0,
17 timestamp_ns: 0,
18 }
19 }
20}
21
22impl Timestamp {
23 pub fn new() -> Self {Timestamp::default()}
26
27 pub fn get_timestamp(mut self) -> Self{
30 let d_timestamp =SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
31 let timestamp_s_temp=d_timestamp.as_secs();
32 let timestamp_ms_temp =d_timestamp.as_micros();
33 let timestamp_ns_temp =d_timestamp.as_nanos();
34
35 self.timestamp_s=timestamp_s_temp;
36 self.timestamp_ms=timestamp_ms_temp;
37 self.timestamp_ns=timestamp_ns_temp;
38
39 self
40 }
41}
42
43pub struct Time {
46 pub year:i32,
47 pub mouth:i8,
48 pub day:i8,
49 pub hour:i8,
50 pub minute:i8,
51 pub secend:i8,
52 timezone_offset:i32, }
54
55impl Default for Time {
56 fn default() -> Self {
57 Time {
58 year: 0,
59 mouth: 0,
60 day: 0,
61 hour: 0,
62 minute: 0,
63 secend: 0,
64 timezone_offset: 8 * 3600,
65 }
66 }
67}
68
69impl Time {
70 pub fn new () ->Self{Time::default()}
73 pub fn is_leap_year(&self) -> bool {
76 if self.year % 400 == 0 {
77 true
78 } else if self.year % 100 == 0 {
79 false
80 } else if self.year % 4 == 0 {
81 true
82 } else {
83 false
84 }
85 }
86
87 pub fn set_timezone(mut self, hours: i32) -> Self {
90 self.timezone_offset = hours * 3600;
91 self
92 }
93
94 pub fn get_time(mut self) -> Self{
96 let t = Timestamp::new().get_timestamp().timestamp_s as i128;
97
98 let t = t + self.timezone_offset as i128;
100
101 let mut days = t / 86400;
103 let other_s = t % 86400;
105
106 let hour = (other_s / 3600) as i8;
108 let minute = ((other_s % 3600) / 60) as i8;
109 let second = (other_s % 60) as i8;
110
111 let mut year: i32 = 1970;
113 loop {
114 self.year = year;
115 let days_in_year = if self.is_leap_year() { 366 } else { 365 };
117 if days < days_in_year { break; }
119 days -= days_in_year;
120 year += 1;
121 }
122
123 self.year = year;
125 let month_days = if self.is_leap_year() {
126 [31,29,31,30,31,30,31,31,30,31,30,31]
127 } else {
128 [31,28,31,30,31,30,31,31,30,31,30,31]
129 };
130
131 let mut month: i8 = 1;
132 for &md in &month_days {
133 if days < md { break; }
135 days -= md;
136 month += 1;
137 }
138
139 let day = (days + 1) as i8;
140
141 self.year = year;
142 self.mouth = month;
143 self.day = day;
144 self.hour = hour;
145 self.minute = minute;
146 self.secend = second;
147
148 self
149 }
150}