Movatterモバイル変換


[0]ホーム

URL:


LoginSignup
10

Go to list of users who liked

6

Share on X(Twitter)

Share on Facebook

Add to Hatena Bookmark

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】toLocaleDateStringで日付フォーマット 🗓

Last updated atPosted at 2022-12-13

toLocaleDateStringで簡単に日付フォーマット

これまで日付フォーマットする時って、getFullYear()とかgetMonth() + 1とかで頑張ってフォーマットしていたんですけど、toLocaleDateString()を使う方法を知り、備忘録として取り上げました。
toLocaleDateString()は、 Dateオブジェクトが持つ日付と時刻の値を、指定したロケールの形式で文字列として返します。

構文

Dateオブジェクト.toLocaleString(locales,options)

例)

constnow=newDate()constdateString=now.toLocaleDateString('ja-JP')console.log(dateString)// → 2022/12/12

optionをつけてさらに自在にフォーマット

constoptions={year:'numeric',month:'short',day:'numeric',weekday:'short',}constnow=newDate()constdateString=now.toLocaleDateString('ja-JP',options)console.log(dateString)// → 2022年12月12日(月)

必要なoptionだけ取ればok
下記は曜日なしの場合

constoptions={year:'numeric',month:'short',day:'numeric',// weekday: 'short', → 曜日オプションコメントアウト}constnow=newDate()constdateString=now.toLocaleDateString('ja-JP',options)console.log(dateString)// → 2022年12月12日

曜日だけ表示したい場合

constoptions={// year: 'numeric',// month: 'short',// day: 'numeric',weekday:'short',}constnow=newDate()constdateString=now.toLocaleDateString('ja-JP',options)console.log(`${dateString}曜日`)// → 月曜日

チャットアプリなどによくある、日付の表示例

引数に日付が渡ってきて、その日付が今日中なら時間表示、昨日なら昨日、一週間いないなら曜日表示、それより前ならyyyy年mm月dd日と表示させる関数の例です。

constdateFormat=(updateDate)=>{constdate=newDate(updateDate);consthours=date.getHours().toString()constminutes=date.getMinutes().toString().padStart(2,'0')consttoday=newDate();constyesterday=newDate(today);yesterday.setDate(today.getDate()-1);constoneWeekAgo=newDate(today);oneWeekAgo.setDate(today.getDate()-7);constoptions={year:"numeric",month:"short",day:"numeric",};constupdateDateString=date.toLocaleDateString("ja-JP",options);consttodayDateString=today.toLocaleDateString("ja-JP",options);constyesterdayDateString=yesterday.toLocaleDateString("ja-JP",options);if(oneWeekAgo.getTime()<date.getTime()){if(updateDateString===todayDateString){return`${hours}:${minutes}`;}elseif(updateDateString===yesterdayDateString){return"昨日";}else{constoptions={weekday:"short",};return`${date.toLocaleDateString("ja-JP",options)}曜日`;}}else{returnupdateDateString;}};

例えば今日が2022/12/13日だとして上記関数で返却された値をconsoleすると下記のようになります。

console.log(dateFormat("2022-12-13 13:30:00"));// → 13:30console.log(dateFormat("2022-12-12 13:30:00"));// → 昨日console.log(dateFormat("2022-12-11 13:30:00"));// → 日曜日console.log(dateFormat("2022-12-6 13:30:00"));// → 2022年12月6日

コード解説

constdate=newDate(updateDate);consthours=date.getHours().toString()constminutes=date.getMinutes().toString().padStart(2,'0')

上記部分では渡ってくる実引数を元にdateオブジェクトのインスタンスを生成し、表示用の時間を定数に格納しています。実引数が今日の日付だった場合はhoursminutesをreturnします。

padStart()とは文字列が指定した長さになるように、現在の文字列を他の文字列で (必要に応じて繰り返して) 延長。延長は、現在の文字列の先頭から適用されます。
minutesにpadStart(2, '0')としているので、2桁になるよう0で埋めてくれる。
例)
padStartなし → 12:0
padStartあり → 12:05

consttoday=newDate();constyesterday=newDate(today);yesterday.setDate(today.getDate()-1);constoneWeekAgo=newDate(today);oneWeekAgo.setDate(today.getDate()-7);

上記部分では本日のdateインスタンスを生成し、setDateで日付をセットして昨日、一週間前を取得しています。
これをif文に使用し、昨日だったら..一週間以内だったら..のように返す値を分ける形です。

constoptions={year:"numeric",month:"short",day:"numeric",};constupdateDateString=date.toLocaleDateString("ja-JP",options);consttodayDateString=today.toLocaleDateString("ja-JP",options);constyesterdayDateString=yesterday.toLocaleDateString("ja-JP",options);

今回の本題、toLocaleDateStringの使用です。
optionを設定し、toLocaleDateStringで表示用に変更したstringをそれぞれ定数に格納しています。

if(oneWeekAgo.getTime()<date.getTime()){if(updateDateString===todayDateString){return`${hours}:${minutes}`;}elseif(updateDateString===yesterdayDateString){return"昨日";}else{constoptions={weekday:"short",};return`${date.toLocaleDateString("ja-JP",options)}曜日`;}}else{returnupdateDateString;}

表示切り替え用の条件文です。if (oneWeekAgo.getTime() < date.getTime())でセットしておいた一週間前の日付と渡ってくる実引数をgetTime()で経過ミリ秒数に変更し、一週間以内かどうか比較しています。
一週間以内だったらさらにネストしたif文で、本日だったら時間を返し、昨日だったら昨日というstringを返しています。
一週間以内だけど今日でも昨日でもない場合に、曜日だけを返したいので、再びtoLocaleDateStringを使用し、曜日だけを取るoptionを設定している流れです。

constoptions={weekday:"short",};return`${date.toLocaleDateString("ja-JP",options)}曜日`;

まとめ

YYYY/mm/ddにフォーマットするだけでも今までは年や月を取得して代入して..ってコネコネして表示させていましたが、toLocaleDateStringだと数行でフォーマットできるんですね!
自分が知らないだけでもっと簡単にできる方法ありそうです..
もっといい方法あるよ!ここの部分、こういうコードに変えてもいいかも!っていう人はコメントでぜひ教えてください!

10

Go to list of users who liked

6
2

Go to list of comments

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
10

Go to list of users who liked

6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?


[8]ページ先頭

©2009-2025 Movatter.jp