1use std::{convert::TryInto, ops::Sub};
2
3use crate::{time::Sign, Time};
4
5impl Time {
7 pub fn new(seconds_since_unix_epoch: u32, offset_in_seconds: i32) -> Self {
9 Time {
10 seconds_since_unix_epoch,
11 offset_in_seconds,
12 sign: offset_in_seconds.into(),
13 }
14 }
15
16 pub fn now_utc() -> Self {
18 let seconds_since_unix_epoch = time::OffsetDateTime::now_utc()
19 .sub(std::time::SystemTime::UNIX_EPOCH)
20 .whole_seconds()
21 .try_into()
22 .expect("this is not year 2038");
23 Self {
24 seconds_since_unix_epoch,
25 offset_in_seconds: 0,
26 sign: Sign::Plus,
27 }
28 }
29
30 pub fn now_local() -> Option<Self> {
32 let now = time::OffsetDateTime::now_utc();
33 let seconds_since_unix_epoch = now
34 .sub(std::time::SystemTime::UNIX_EPOCH)
35 .whole_seconds()
36 .try_into()
37 .expect("this is not year 2038");
38 let offset_in_seconds = time::UtcOffset::local_offset_at(now).ok()?.whole_seconds();
41 Self {
42 seconds_since_unix_epoch,
43 offset_in_seconds,
44 sign: offset_in_seconds.into(),
45 }
46 .into()
47 }
48
49 pub fn now_local_or_utc() -> Self {
51 let now = time::OffsetDateTime::now_utc();
52 let seconds_since_unix_epoch = now
53 .sub(std::time::SystemTime::UNIX_EPOCH)
54 .whole_seconds()
55 .try_into()
56 .expect("this is not year 2038");
57 let offset_in_seconds = time::UtcOffset::local_offset_at(now)
60 .map(|ofs| ofs.whole_seconds())
61 .unwrap_or(0);
62 Self {
63 seconds_since_unix_epoch,
64 offset_in_seconds,
65 sign: offset_in_seconds.into(),
66 }
67 }
68}