diff --git a/vlib/time/time.v b/vlib/time/time.v index 971a98dfe3..f02ca5ad23 100644 --- a/vlib/time/time.v +++ b/vlib/time/time.v @@ -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 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 @@ -323,4 +329,17 @@ pub fn sleep_ms(n int) { // Determine whether a year is a leap year. pub fn is_leap_year(year int) bool { return (year%4 == 0) && (year%100 != 0 || year%400 == 0) -} \ No newline at end of file +} + +// 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] + } +} diff --git a/vlib/time/time_test.v b/vlib/time/time_test.v index 6f58eeb4c5..c3122fa2ae 100644 --- a/vlib/time/time_test.v +++ b/vlib/time/time_test.v @@ -14,4 +14,26 @@ fn test_is_leap_year() { assert time.is_leap_year(1996) == true assert time.is_leap_year(1997) == false -} \ No newline at end of file +} + +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 +}