日付に月を足したり引いたりする数式を探しています。年と月だけを知る必要があるため、日は無視できます。
これは私が思いついた追加の月の疑似コードです:
OldYear = 2012 // current year
OldMonth = 3 // current month
AddMonths = 0 // the months to be added
FooBar = OldMonth + AddMonths
NewYear = OldYear + FooBar / 12
NewMonth = FooBar % 12
IF NewMonth = 0
NewYear = NewYear - 1
NewMonth = 12
END IF
// set AddMonths to 0 and the result will be 2012.03
// set AddMonths to 6 and the result will be 2012.09
// set AddMonths to 9 and the result will be 2012.12
// set AddMonths to 11 and the result will be 2013.02
// set AddMonths to 23 and the result will be 2014.02
// set AddMonths to 38 and the result will be 2015.05
それは本当にうまく機能しますが、もっと良い方法はありますか? IF NewMonth = 0 の再調整の必要性はあまり好きではありません。
しかし、私の実際の問題は、月を減算する対応する式を思いつくことができなかったことです。いろいろ試しましたが、どれもうまくいかず、気が狂ってしまいました。どんな助けでも大歓迎です!