From: daurnimator Date: Wed, 24 Jul 2013 15:53:24 +0000 (-0400) Subject: src/timetable: Fix timestamp function; add test X-Git-Url: https://git.madduck.net/etc/awesome.git/commitdiff_plain/86e57ee7249734545974d4b8ba2de3bcea6575a3?ds=inline src/timetable: Fix timestamp function; add test --- diff --git a/spec/timetable_spec.lua b/spec/timetable_spec.lua index a72a0f9..a80b9ad 100644 --- a/spec/timetable_spec.lua +++ b/spec/timetable_spec.lua @@ -34,4 +34,18 @@ describe ( "Time table library" , function ( ) assert_same_wday ( 2013 , 7 , 28 ) assert_same_wday ( 2013 , 7 , 29 ) end ) + + local function native_timestamp ( year , month , day ) + return assert ( tonumber ( assert ( io.popen ( + string.format('date -u -d "%d-%d-%d" +%%s', year , month , day ) + ) ):read "*l" ) ) + end + + it ( "Timestamp creation is valid" , function ( ) + for y=1950,2013 do + for m=1,12 do + assert.same ( native_timestamp ( y,m,1 ) , timetable.timestamp(y,m,1,0,0,0) ) + end + end + end) end ) diff --git a/src/timetable.lua b/src/timetable.lua index b58ad0f..e7f2816 100644 --- a/src/timetable.lua +++ b/src/timetable.lua @@ -102,12 +102,16 @@ local function normalise ( year , month , day , hour , min , sec ) return year , month , day , hour , min , sec end +local leap_years_since_1970 = leap_years_since ( 1970 ) local function timestamp ( year , month , day , hour , min , sec ) - return 60*60*24*( - year * year_length ( year ) - + month * month_length ( month , year ) - + day - ) + year , month , day , hour , min , sec = normalise ( year , month , day , hour , min , sec ) + + local days_since_epoch = day_of_year ( day , month , year ) + + 365 * ( year - 1970 ) + -- Each leap year adds one day + + ( leap_years_since ( year - 1 ) - leap_years_since_1970 ) - 1 + + return days_since_epoch * 60*60*24 + hour * (60*60) + min * 60 + sec