time_core/util.rs
1//! Utility functions.
2
3/// Returns if the provided year is a leap year in the proleptic Gregorian calendar. Uses
4/// [astronomical year numbering](https://en.wikipedia.org/wiki/Astronomical_year_numbering).
5///
6/// ```rust
7/// # use time::util::is_leap_year;
8/// assert!(!is_leap_year(1900));
9/// assert!(is_leap_year(2000));
10/// assert!(is_leap_year(2004));
11/// assert!(!is_leap_year(2005));
12/// assert!(!is_leap_year(2100));
13/// ```
14pub const fn is_leap_year(year: i32) -> bool {
15 let d = if year % 100 == 0 { 15 } else { 3 };
16 year & d == 0
17}
18
19/// Get the number of calendar days in a given year.
20///
21/// The returned value will always be either 365 or 366.
22///
23/// ```rust
24/// # use time::util::days_in_year;
25/// assert_eq!(days_in_year(1900), 365);
26/// assert_eq!(days_in_year(2000), 366);
27/// assert_eq!(days_in_year(2004), 366);
28/// assert_eq!(days_in_year(2005), 365);
29/// assert_eq!(days_in_year(2100), 365);
30/// ```
31pub const fn days_in_year(year: i32) -> u16 {
32 if is_leap_year(year) {
33 366
34 } else {
35 365
36 }
37}
38
39/// Get the number of weeks in the ISO year.
40///
41/// The returned value will always be either 52 or 53.
42///
43/// ```rust
44/// # use time::util::weeks_in_year;
45/// assert_eq!(weeks_in_year(2019), 52);
46/// assert_eq!(weeks_in_year(2020), 53);
47/// ```
48pub const fn weeks_in_year(year: i32) -> u8 {
49 match year % 400 {
50 -396 | -391 | -385 | -380 | -374 | -368 | -363 | -357 | -352 | -346 | -340 | -335
51 | -329 | -324 | -318 | -312 | -307 | -301 | -295 | -289 | -284 | -278 | -272 | -267
52 | -261 | -256 | -250 | -244 | -239 | -233 | -228 | -222 | -216 | -211 | -205 | -199
53 | -193 | -188 | -182 | -176 | -171 | -165 | -160 | -154 | -148 | -143 | -137 | -132
54 | -126 | -120 | -115 | -109 | -104 | -97 | -92 | -86 | -80 | -75 | -69 | -64 | -58
55 | -52 | -47 | -41 | -36 | -30 | -24 | -19 | -13 | -8 | -2 | 4 | 9 | 15 | 20 | 26 | 32
56 | 37 | 43 | 48 | 54 | 60 | 65 | 71 | 76 | 82 | 88 | 93 | 99 | 105 | 111 | 116 | 122
57 | 128 | 133 | 139 | 144 | 150 | 156 | 161 | 167 | 172 | 178 | 184 | 189 | 195 | 201
58 | 207 | 212 | 218 | 224 | 229 | 235 | 240 | 246 | 252 | 257 | 263 | 268 | 274 | 280
59 | 285 | 291 | 296 | 303 | 308 | 314 | 320 | 325 | 331 | 336 | 342 | 348 | 353 | 359
60 | 364 | 370 | 376 | 381 | 387 | 392 | 398 => 53,
61 _ => 52,
62 }
63}