日付オブジェクトから年/月/日を取得するにはどうすればいいですか? 質問する

日付オブジェクトから年/月/日を取得するにはどうすればいいですか? 質問する

alert(dateObj)与えるWed Dec 30 2009 00:00:00 GMT+0800

フォーマット内の日付を取得するにはどうすればいいですか2009/12/30?

ベストアンサー1

const dateObj = new Date();
const month   = dateObj.getUTCMonth() + 1; // months from 1-12
const day     = dateObj.getUTCDate();
const year    = dateObj.getUTCFullYear();

const newDate = year + "/" + month + "/" + day;

// Using template literals:
const newDate = `${year}/${month}/${day}`;

// Using padded values, so that 2023/1/7 becomes 2023/01/07
const pMonth        = month.toString().padStart(2,"0");
const pDay          = day.toString().padStart(2,"0");
const newPaddedDate = `${year}/${pMonth}/${pDay}`;

または新しい日付を設定して上記の値を指定することもできます

おすすめ記事