v / vlib / time / chrono.v
35 lines · 32 sloc · 1.45 KB · c51d30bf5309653c6b573ec815268e69a78ea8cc
Raw
1module time
2
3// days_from_unix_epoch - return the number of days since the Unix epoch 1970-01-01.
4// A detailed description of the algorithm here is in:
5// http://howardhinnant.github.io/date_algorithms.html
6// Note that function will return negative values for days before 1970-01-01.
7pub fn days_from_unix_epoch(year int, month int, day int) int {
8 y := if month <= 2 { year - 1 } else { year }
9 era := y / 400
10 year_of_the_era := y - era * 400 // [0, 399]
11 day_of_year := (153 * (month + (if month > 2 { -3 } else { 9 })) + 2) / 5 + day - 1 // [0, 365]
12 day_of_the_era := year_of_the_era * 365 + year_of_the_era / 4 - year_of_the_era / 100 +
13 day_of_year // [0, 146096]
14 return era * 146097 + day_of_the_era - 719468
15}
16
17// days_from_unix_epoch - return the number of days since the Unix epoch 1970-01-01.
18// A detailed description of the algorithm here is in:
19// http://howardhinnant.github.io/date_algorithms.html
20// Note that method will return negative values for days before 1970-01-01.
21@[inline]
22pub fn (t Time) days_from_unix_epoch() int {
23 return days_from_unix_epoch(t.year, t.month, t.day)
24}
25
26// date_from_days_after_unix_epoch - convert number of `days` after the unix epoch 1970-01-01, to a Time.
27// Only the year, month and day of the returned Time will be set, everything else will be 0.
28pub fn date_from_days_after_unix_epoch(days int) Time {
29 year, month, day := calculate_date_from_day_offset(i64(days))
30 return Time{
31 year: year
32 month: month
33 day: day
34 }
35}
36