A challenge: adding months to a date?
David Bovill
david at openpartnership.net
Sun May 13 13:34:35 EDT 2007
Getting there :)
But still fails the unit tests - resulting in:
1
Failed adding 1 to 2002,1,31,1,0,0,5. Resulted in 1
2
Failed adding 2 to 2002,1,31,1,0,0,5. Resulted in 2
4
5
6
7
8
9
10
10
Failed adding 10 to 2002,1,31,1,0,0,5. Resulted in 10
Which looks like is kind of one out of the loop - NB I like your evaluation
of leap years - is that all there is to it? Taking a look at the code now to
see where it is going wrong...
on mouseUp
-- unit test
put "2002,1,31,1,0,0,5" into abbeyStartDate
put 1 into lastMonth
repeat with statementNumber = 1 to 10
put item 2 of date_AddMonth(statementNumber, abbeyStartDate) into
someMonth
put someMonth
if statementNumber mod 12 is not (someMonth - 1) then
put merge("Failed adding [[statementNumber]] to
[[abbeyStartDate]]. Resulted in [[someMonth]]")
end if
end repeat
end mouseUp
function date_AddMonth monthNum, startDate
convert startDate to dateItems # does not work if startDate is a
system date
put item 3 of startDate into theDay
put 1 into item 3 of startDate
add monthNum to item 2 of startDate
convert startDate from dateItems to dateItems
put item 2 of startDate into theMonth
put item 1 of startDate into theYear
put getMaxDays(theMonth, theYear) into maxDay
if theDay > maxDay then
put maxDay into theDay
end if
put theDay into item 3 of startDate
--convert startDate from dateItems to <favorite date format>
return startDate
end date_AddMonth
function getMaxDays theMonth, theYear
put "1,January,3,March,5,May,7,July,8,August,10,October,12,December"
into Months31
put "4,April,6,June,9,September,11,November" into Months30
if theMonth is among the items of Months31 then
put 31 into HowManyDays
else if theMonth is among the items of Months30 then
put 30 into HowManyDays
else --February
if (theYear mod 400 = 0) or (theYear mod 100 <> 0) and (theYear mod
4 = 0) then
put 29 into HowManyDays -- leap year
else
put 28 into HowManyDays
end if
end if
return HowManyDays
end getMaxDays
More information about the use-livecode
mailing list