
JavaScriptの日時表示にget〇〇
JavaScriptの日時表示の際にほとんどの人はnew Date()で取得してget〇〇を使用して年月日を取得すると習うだろう。
const now = new Date()
const year = now.getFullYear()
const month = now.getMonth() + 1
const date = now.getDate()
const addZero = n => ('0' + n).slice(-2)
console.log(`${year}/${addZero(month)}/${addZero(date)}`)
// 2021/12/30
しかし、これは初心者がnew Date()から年月日などの取得方法を習得するためにget〇〇を使用されている。
実際の仕事では初心者でなければtoLocaleStringまたはIntl.DateTimeFormatが使用されることが多い。
toLocaleStringで年月日
toLocaleStringで年月日を表示するには以下のようにする。
'2-digit' を指定することで1月1日の場合1/1ではなく01/01と1桁の場合0付きで表示することができる。
const d = new Date()
const result = d.toLocaleString('ja-JP', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
console.log(result)
// 2021/12/30
Intl.DateTimeFormatで年月日
Intl.DateTimeFormatで年月日を表示するには以下のようにする。
toLocaleStringと似ているが、formatter定数にnew Intl.DateTimeFormatを入れてformatter.format()でnew Date()をyyyy/mm/dd形式に変換できるので再利用がしやすい。
const d = new Date()
const formatter = new Intl.DateTimeFormat('ja-JP', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
console.log(formatter.format(d))
// 2021/12/30
見ての通りIntl.DateTimeFormatのほうが再利用しやすく使い勝手が良いので、もしyyyy/mm/dd形式などの日時変換処理を行う場合はIntl.DateTimeFormatを使用したほうが良いだろう。