LoginSignup
11
8

More than 5 years have passed since last update.

JavaScriptで月の加算

Last updated at Posted at 2016-10-22

加算前の日付が月末だと、単純に月の加算をすると意図した結果にならない。
意図する結果については場合によると思うが、今回は加算した月の末日としたい場合。
例えば、2016/01/31に1ヶ月後を取得したら2016/02/29としたいが、以下のように単純に月を加算すると、実行結果は2016/03/02となる。

function addMonths(date, months) {
    var resultDate = new Date(date.getTime());
    resultDate.setMonth(date.getMonth() + 1);
    return resultDate;
}

var date = addMonths(new Date("2016/01/31"), 1);

これは月を加算すると2016/02/31となり、2月は29日(2016年は閏年)までしかなく、2日はみ出てしまうから。

月末日に調整したい場合は、以下のように日にちを判定して補正してあげれば2016/02/29となる。
setDate(0)は前月の月末となる)

function addMonths(date, months) {
    var resultDate = new Date(date.getTime());
    resultDate.setMonth(date.getMonth() + 1);
    if (date.getDate() > date.getDate()) {
        resultDate.setDate(0);
    }
    return resultDate;
}

var date = addMonths(new Date("2016/01/31"), 1);
11
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
8