Arne
Arne

Reputation: 272

Applescript: Addition of months via adding multiples of days with strange behaviour

So I am trying to define a function that adds months. But already in the beginning, I stumble on the following issue.

set testdate to (current date)
set the month of testdate to (1 as integer)
set the day of testdate to (1 as integer)

tell testdate to set {day} to {day + 32 * 4}
testdate

I would expect to get at least an output of a date in May 2020 (of course not first of May, but something in the beginning), however, the output is

date "Montag, 26. August 2019 um 15:53:13"

instead. Can someone explain to me, please?

If I change, for instance, the "4" above into a "3", then I get the expected

date "Montag, 6. April 2020 um 16:06:21"

With the help of red_menace, I was able to implement the following procedure that adds months.

on addMonths onto oldDate by m
    copy oldDate to newDate
    set newDate to newDate + (days * 31 * m)
    if newDate's day is not oldDate's day then set newDate to (newDate) - ((newDate's day) - (oldDate's day)) * days
    return newDate
end addMonths

(However, an explanation of why this bug happens is still not there.)

Upvotes: 1

Views: 261

Answers (1)

red_menace
red_menace

Reputation: 3422

I don't think it is a bug so much as it just may be a result of the way the date object is implemented internally (my guess for that is that 127 works, but 128 does not). The day property is for the day of the month (1 - 31), so cheating a little by using out of bounds days might work for overflowing a few days into nearby months, but they probably didn't bother checking for something exceeding the size of the allotted structure.

When manipulating dates, the normal procedure for a time difference is to add or subtract the number of seconds. The date class has various properties such as day and month, but there are also constants such as days or hours, which contain the number of seconds in a day or hour, respectively (they only go to weeks, since months do not have a fixed number of days):

set testdate to (current date) -- get a date object
set the month of testdate to 1 -- set new month
set the day of testdate to 1 -- set new day

log 24 * hours
log days
return testdate + (days * 32 * 4) -- add to the date

See the date class reference in the AppleScript Language Guide.

Upvotes: 1

Related Questions