JavaScript Date getMonth() メソッドの使い方

JavaScript の Date オブジェクトの getMonth() メソッドは、日付オブジェクトの月の部分を返します。このメソッドが返す月は 0 から始まって数えられ、0 は 1 月、1 は 2 月となります。

getMonth()メソッドの利用例を以下に示します。

const date = new Date();
const month = date.getMonth();
console.log(month); // 输出当前月份的数字,从0开始计数

getMonth()メソッドとその他のメソッド、例えばgetDay()メソッドを組み合わせて日付オブジェクトの日付部分を取得することもできます

const date = new Date();
const day = date.getDate();
const month = date.getMonth();
console.log(`${day}/${month+1}`); // 输出当前日期和月份,注意月份需要加1

上の例では、getDate()メソッドで日付オブジェクトの日付部分を取得し、さらにgetMonth()メソッドで月部分を取得しました。getMonth()メソッドで返される月は0から数え始めるため、出力時に月を1加算しています。

お役に立てたら幸いです!

bannerAds