mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
time: days_in_month()
This commit is contained in:
parent
82ed0156c5
commit
1ce295b683
@ -6,6 +6,11 @@ module time
|
|||||||
|
|
||||||
import rand
|
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>
|
#include <time.h>
|
||||||
struct Time {
|
struct Time {
|
||||||
pub:
|
pub:
|
||||||
@ -18,6 +23,7 @@ pub:
|
|||||||
uni int // TODO it's safe to use "unix" now
|
uni int // TODO it's safe to use "unix" now
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
fn C.localtime(int) *C.tm
|
fn C.localtime(int) *C.tm
|
||||||
|
|
||||||
fn remove_me_when_c_bug_is_fixed() { // TODO
|
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 {
|
pub fn is_leap_year(year int) bool {
|
||||||
return (year%4 == 0) && (year%100 != 0 || year%400 == 0)
|
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]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -15,3 +15,25 @@ fn test_is_leap_year() {
|
|||||||
assert time.is_leap_year(1996) == true
|
assert time.is_leap_year(1996) == true
|
||||||
assert time.is_leap_year(1997) == false
|
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
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user