time: days_in_month()

pull/1139/head
nxshock 2019-07-14 19:43:57 +05:00 committed by Alexander Medvednikov
parent 82ed0156c5
commit 1ce295b683
2 changed files with 43 additions and 2 deletions

View File

@ -6,6 +6,11 @@ module time
import rand
// https://en.wikipedia.org/wiki/Month#Julian_and_Gregorian_calendars
const (
MonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
)
#include <time.h>
struct Time {
pub:
@ -18,6 +23,7 @@ pub:
uni int // TODO it's safe to use "unix" now
}
fn C.localtime(int) *C.tm
fn remove_me_when_c_bug_is_fixed() { // TODO
@ -324,3 +330,16 @@ pub fn sleep_ms(n int) {
pub fn is_leap_year(year int) bool {
return (year%4 == 0) && (year%100 != 0 || year%400 == 0)
}
// Returns number of days in month
pub fn days_in_month(month, year int) ?int {
if month > 12 || month < 1 {
return error('Invalid month: $month')
}
if month == 2 {
return MonthDays[month-1] + if is_leap_year(year) {1} else {0}
} else {
return MonthDays[month-1]
}
}

View File

@ -15,3 +15,25 @@ fn test_is_leap_year() {
assert time.is_leap_year(1996) == true
assert time.is_leap_year(1997) == false
}
fn check(month, year, expectedDays int) bool {
return time.days_in_month(month, year) or {
return false
}
}
fn test_days_in_month() {
assert check(1, 2001, 31) // January
assert check(2, 2001, 28) // February
assert check(2, 2000, 29) // February (leap)
assert check(3, 2001, 31) // March
assert check(4, 2001, 30) // April
assert check(5, 2001, 31) // May
assert check(6, 2001, 30) // June
assert check(7, 2001, 31) // July
assert check(8, 2001, 31) // August
assert check(9, 2001, 30) // September
assert check(10, 2001, 31) // October
assert check(11, 2001, 30) // November
assert check(12, 2001, 31) // December
}