1 use crate::date::Date;
2 use std::time::{SystemTime, UNIX_EPOCH};
3
4 // Timestamp of 2016-03-01 00:00:00 in UTC.
5 const BASE: u64 = 1456790400;
6 const BASE_YEAR: u16 = 2016;
7 const BASE_MONTH: u8 = 3;
8
9 // Days between leap days.
10 const CYCLE: u64 = 365 * 4 + 1;
11
12 const DAYS_BY_MONTH: [u8; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
13
today() -> Date14 pub fn today() -> Date {
15 let default = Date {
16 year: 2019,
17 month: 1,
18 day: 1,
19 };
20 try_today().unwrap_or(default)
21 }
22
try_today() -> Option<Date>23 fn try_today() -> Option<Date> {
24 let now = SystemTime::now();
25 let since_epoch = now.duration_since(UNIX_EPOCH).ok()?;
26 let secs = since_epoch.as_secs();
27
28 let approx_days = secs.checked_sub(BASE)? / 60 / 60 / 24;
29 let cycle = approx_days / CYCLE;
30 let mut rem = approx_days % CYCLE;
31
32 let mut year = BASE_YEAR + cycle as u16 * 4;
33 let mut month = BASE_MONTH;
34 loop {
35 let days_in_month = DAYS_BY_MONTH[month as usize - 1];
36 if rem < days_in_month as u64 {
37 let day = rem as u8 + 1;
38 return Some(Date { year, month, day });
39 }
40 rem -= days_in_month as u64;
41 year += (month == 12) as u16;
42 month = month % 12 + 1;
43 }
44 }
45