Applescript:通过添加具有奇怪行为的天数来增加月份

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

所以我试图定义一个增加月份的函数。但是一开始,我偶然发现了以下问题。

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

我希望至少得到 2020 年 5 月的日期输出(当然不是五月一日,而是开始的日期),但是,输出是

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

相反。有人可以给我解释一下吗?

例如,如果我将上面的“4”更改为“3”,那么我将得到预期的结果

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

在 red_menace 的帮助下,我能够实现以下增加月份的过程。

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

(但是,仍然没有解释为什么会出现此错误。)

我不认为这是一个错误,因为它可能只是日期对象内部实现方式的结果(我的猜测是 127 有效,但 128 无效)。 day 属性 是一个月中的第几天 (1 - 31),因此通过使用超出范围的日期来作弊可能会在附近的月份中溢出几天,但他们可能没有不要费心检查超出分配结构大小的东西。

处理日期时,时差的正常程序是加上或减去秒数。日期 class 具有各种属性,例如 daymonth,但也有常量,例如 dayshours,其中包含秒数分别是一天或一小时(他们只去 weeks,因为月份没有固定的天数):

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

请参阅 AppleScript 语言指南中的 date class reference