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