git_date/time/
init.rs

1use std::{convert::TryInto, ops::Sub};
2
3use crate::{time::Sign, Time};
4
5/// Instantiation
6impl Time {
7    /// Create a new instance from seconds and offset.
8    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    /// Return the current time without figuring out a timezone offset
17    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    /// Return the current local time, or `None` if the local time wasn't available.
31    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        // TODO: make this work without cfg(unsound_local_offset), see
39        //       https://github.com/time-rs/time/issues/293#issuecomment-909158529
40        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    /// Return the current local time, or the one at UTC if the local time wasn't available.
50    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        // TODO: make this work without cfg(unsound_local_offset), see
58        //       https://github.com/time-rs/time/issues/293#issuecomment-909158529
59        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}