A challenge: adding months to a date?
David Bovill
david at openpartnership.net
Mon May 14 08:04:49 EDT 2007
Does anyone know exactly what the convert is doing with the times? I
modified Kens code so it also returns the best guess date as well as working
out the month and year - that is if there is no exact match it return s the
last day of that month....
And the Unit test returns this:
Thu, 28 Feb 2002 01:00:00 +0000
Sun, 31 Mar 2002 02:00:00 +0000
Tue, 30 Apr 2002 02:00:00 +0000
Fri, 31 May 2002 02:00:00 +0000
Sun, 30 Jun 2002 02:00:00 +0000
Wed, 31 Jul 2002 02:00:00 +0000
Sat, 31 Aug 2002 02:00:00 +0000
Mon, 30 Sep 2002 02:00:00 +0000
Thu, 31 Oct 2002 01:00:00 +0000
Sat, 30 Nov 2002 01:00:00 +0000
Wed, 31 Dec 2003 01:00:00 +0000
Fri, 31 Jan 2003 01:00:00 +0000
Fri, 28 Feb 2003 01:00:00 +0000
Mon, 31 Mar 2003 02:00:00 +0000
1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
Which passes - as each month is incremental, as are the month numbers. But -
why do the times change from October to February. Note I added the 2am line
to the script to ensure convert does not subtract the odd day now and
then...
Here is the modified code:
on mouseUp
put "2002,1,31,1,0,0,5" into startDate
put 1 into lastMonth
put lastMonth into endMonths
repeat with statementNumber = 1 to 14
set the cursor to busy
date_AddMonth statementNumber, startDate, endMonth, endYear
put the result
put space & endMonth after endMonths
if statementNumber mod 12 is not (endMonth - 1) then
put merge("Failed adding [[statementNumber]] to
[[abbeyStartDate]]. Resulted in [[someMonth]]")
end if
end repeat
put endMonths
end mouseUp
on date_AddMonth monthsToAdd, startDate, @endMonth, @endYear
-- thanks to Ken Ray <kray at sonsothunder.com> !
put startDate into someDate
convert someDate to dateItems
put item 1 of someDate into tYear
put item 2 of someDate into tMonth
put (monthsToAdd+tMonth) mod 12 into endMonth
if endMonth = 0 then put 12 into endMonth
put ((monthsToAdd+tMonth) div 12) + tYear into endYear
put endYear into item 1 of someDate
put endMonth into item 2 of someDate
put date_MaxDaysInMonth(endMonth, endYear) into item 3 of someDate
put 2 into item 4 of someDate # seems to be required !!!
convert someDate to internet date
return someDate
end date_AddMonth
function date_MaxDaysInMonth theMonth, theYear
-- thanks to Björnke von Gierke <bvg at mac.com> !
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 date_MaxDaysInMonth
More information about the use-livecode
mailing list