0
0

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.

moment.jsは使わず、日付の変換にDateオブジェクトを使う

Posted at

みんなが使ってるmoment.js
便利ですが、ちょっと日付を変換したいだけなのに
いちいちnpm installしたり、require()したりで少々めんどくさくもあります。

今日はもしかしたら皆さんは日常的に使われているかもしれませんが、Javascriptの標準組み込みオブジェクトである、
Dateオブジェクトを使っていきたいと思います。

日付の変換方法

const date = new Date("2020-11-18T13:05:08.357Z") //Dateオブジェクトのインスタンスを作成 詳しくはDateコンストラクタにて
const date_formatted = date.toLocaleDateString("ja-JP") //日本で使われるフォーマットを指定
console.log(date_formatted);//=>2020/11/18
出力結果
2020/11/18

このように簡単に日付の変換を行えます。

Dateコンストラクタ

以下の形でDateインスタンスを作成できるようです。

1.引数なし
2.時刻値またはタイムスタンプ値
3.タイムスタンプ文字列
4.独立した日付と時刻の成分の値

詳細は以下で=>https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

日付の変換

Dateインスタンスのメソッドの一つであるtoLocaleDateStringを使います。

構文
dateObj.toLocaleDateString([locales[, options]])

localesには地域名、言語名などを指定できます。
なので、ここを"ar-EG"なんかにすると、

~
const date_formatted = date.toLocaleDateString("ar-EG") 
console.log(date_formatted);
出力結果
الأربعاء، ١٨ نوفمبر ٢٠٢٠ 

このようにアラビア語にしたりもできます。

次にoptionsには出力時のオプションなどを指定できます。

const format_options = {
        weekday: "long",
        year: "numeric",
        month: "long",
        day: "numeric",
      };
const date = new Date("2020-11-18T13:05:08.357Z",format_options) 
const date_formatted = date.toLocaleDateString("ja-JP") 
console.log(date_formatted);
出力結果
2020年11月18日水曜日

オプション等の詳細はここを参照=>https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

おわりに

所詮中学生の浅知恵の可能性もあるので、鵜呑みにはしないでください。
今日は個人的な発見を書いてだけの記事を読んでくださりありがとうございました。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?