Intl.DateTimeFormatを使って西暦を和暦に変換する

image.png (59.9 kB)

TOC

JavaScriptを書いていて、西暦から和暦に変換をする機会があったので、自分自身のメモとして残しておこうと思います。

実装

今回は2022年09月01日を、和暦に変換してみたいと思います。 標準組み込みオブジェクトを利用すれば、非常に簡単に変換することができます。

const date = new Date(2022, 8, 1)
const japaneseCalendar = new Intl.DateTimeFormat('ja-JP-u-ca-japanese', {era: 'long'}).format(date)
console.log(japaneseCalendar)
// => 令和4/9/1

Intlオブジェクト

Intlオブジェクトは ECMAScript の国際化 API の名前空間で、言語に依存した文字列の比較、数値の書式化と、日付の書式化を提供するオブジェクトです。 今回利用するIntl.DateTimeFormat()以外にも、Intl.Collator()Intl.DisplayNames()等、様々なコンストラクターが存在します。

・参考 https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Intl

Intl.DateTimeFormat()

Intl.DateTimeFormat オブジェクトは指定した言語の書籍にフォーマットするコンストラクターです。 このコンストラクターは任意で引数を2つ指定することができます。

  • 第1引数: locales
  • 第2引数: options
new Intl.DateTimeFormat(locales, options).format()

・参考 https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#options_%E3%81%AE%E4%BD%BF%E7%94%A8

locales

第1引数のlocalesではBCP47言語タグの文字列 or 配列を受け取ります。

new Intl.DateTimeFormat('ja-JP-u-ca-japanese').format()
// or
new Intl.DateTimeFormat(['ja-JP-u-ca-japanese']).format()

options

第2引数のoptionsはObject形式で、年・月・日の書式設定を指定することができます。

new Intl.DateTimeFormat('en-US', {
  year: 'numeric', // ... 2019・2022
  month: 'long', // ... March・June
  day: '2-digit' // ... 01・05
}).format()

和暦に変換する際は、このoptionsのera'long'を指定します。 eraには他にも'short''narrow'を指定することができます。

new Intl.DateTimeFormat('ja-JP-u-ca-japanese', {era: 'long'}).format()

注意点

Node.jsで利用する場合は、バージョンによって出力される形式に際があるので、利用する際は注意してください。

// v14.15.0
new Intl.DateTimeFormat('ja-JP-u-ca-japanese', {era: 'long'}).format()
// => 令和4年9月1日

// v16.15.0
new Intl.DateTimeFormat('ja-JP-u-ca-japanese', {era: 'long'}).format()
// => 令和4/9/13
CONTACT
© 2023, Kakkiii All Rights Reserved.