2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

(JavaScript)日付表示の簡便なフォーマット方法を見つけた

Last updated at Posted at 2020-08-22
const fmt_1 = new Intl.DateTimeFormat('ja', {
  year: 'numeric', month: 'long', day: 'numeric'
})
console.log(
  fmt_1.format(new Date())
)
//2020年8月22日
const fmt_2 = new Intl.DateTimeFormat('ja', {
  year: 'numeric', month: '2-digit', day: '2-digit'
})
console.log(
  fmt_2.format(new Date())
)
//2020/08/22
const fmt_3 = new Intl.DateTimeFormat('ja', {
  year: 'numeric', month: 'long', day: 'numeric',
  hour: 'numeric', minute: 'numeric',
  hour12: true
})
console.log(
  fmt_3.format(new Date())
)
//2020年8月22日 午後8:58
const fmt_4 = new Intl.DateTimeFormat('ja', {
  year: '2-digit', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', second: '2-digit',
  hour12: false
})
console.log(
  fmt_4.format(new Date())
)
//20/08/22 20:58:05

各プロパティ用の値は以下から

Intl.DateTimeFormat
by MDN Contributors (CC BY-SA 2.5)
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat


フォーマット用のインスタンスを作っておけば、後からいくらでも再利用できるというわけです。

new Date().getFullYear()で年を求め、new Date().getMonth() + 1で月を求め、時間が12以上だったら12を引いて『午後』を付けて…」などとしていたのが馬鹿馬鹿しくなってきますね…。

2
4
1

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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?