fastdate/sys/mod.rs
1use std::time::{SystemTime, UNIX_EPOCH};
2
3#[cfg(any(target_arch = "wasm32", target_env = "sgx"))]
4#[path = "stub.rs"]
5mod inner;
6
7#[cfg(unix)]
8#[path = "unix.rs"]
9mod inner;
10
11#[cfg(windows)]
12#[path = "windows.rs"]
13mod inner;
14
15/// A record specifying a time value in seconds and nanoseconds, where
16/// nanoseconds represent the offset from the given second.
17///
18/// For example a timespec of 1.2 seconds after the beginning of the epoch would
19/// be represented as {sec: 1, nsec: 200000000}.
20pub struct Timespec {
21 pub sec: i64,
22 pub nsec: i32,
23}
24
25impl Timespec {
26 /// Constructs a timespec representing the current time in UTC.
27 pub fn now() -> Timespec {
28 let st = SystemTime::now()
29 .duration_since(UNIX_EPOCH)
30 .expect("system time before Unix epoch");
31 Timespec {
32 sec: st.as_secs() as i64,
33 nsec: st.subsec_nanos() as i32,
34 }
35 }
36
37 /// Converts this timespec into the system's local time.
38 pub fn local(self) -> Tm {
39 let mut tm = Tm {
40 tm_sec: 0,
41 tm_min: 0,
42 tm_hour: 0,
43 tm_mday: 0,
44 tm_mon: 0,
45 tm_year: 0,
46 tm_wday: 0,
47 tm_yday: 0,
48 tm_isdst: 0,
49 tm_utcoff: 0,
50 tm_nsec: 0,
51 };
52 inner::time_to_local_tm(self.sec, &mut tm);
53 tm.tm_nsec = self.nsec;
54 tm
55 }
56}
57
58/// Holds a calendar date and time broken down into its components (year, month,
59/// day, and so on), also called a broken-down time value.
60// FIXME: use c_int instead of i32?
61#[repr(C)]
62pub struct Tm {
63 /// Seconds after the minute - [0, 60]
64 pub tm_sec: i32,
65
66 /// Minutes after the hour - [0, 59]
67 pub tm_min: i32,
68
69 /// Hours after midnight - [0, 23]
70 pub tm_hour: i32,
71
72 /// Day of the month - [1, 31]
73 pub tm_mday: i32,
74
75 /// Months since January - [0, 11]
76 pub tm_mon: i32,
77
78 /// Years since 1900
79 pub tm_year: i32,
80
81 /// Days since Sunday - [0, 6]. 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
82 pub tm_wday: i32,
83
84 /// Days since January 1 - [0, 365]
85 pub tm_yday: i32,
86
87 /// Daylight Saving Time flag.
88 ///
89 /// This value is positive if Daylight Saving Time is in effect, zero if
90 /// Daylight Saving Time is not in effect, and negative if this information
91 /// is not available.
92 pub tm_isdst: i32,
93
94 /// Identifies the time zone that was used to compute this broken-down time
95 /// value, including any adjustment for Daylight Saving Time. This is the
96 /// number of seconds east of UTC. For example, for U.S. Pacific Daylight
97 /// Time, the value is `-7*60*60 = -25200`.
98 pub tm_utcoff: i32,
99
100 /// Nanoseconds after the second - [0, 10<sup>9</sup> - 1]
101 pub tm_nsec: i32,
102}
103
104impl Tm {
105 /// Convert time to the seconds from January 1, 1970
106 pub fn to_timespec(&self) -> Timespec {
107 let sec = match self.tm_utcoff {
108 0 => inner::utc_tm_to_time(self),
109 _ => inner::local_tm_to_time(self),
110 };
111 Timespec {
112 sec,
113 nsec: self.tm_nsec,
114 }
115 }
116}