概要
この関数を知らなかったのでメモ。
Date.prototype.toLocaleDateString()
内容
何も指定しない場合
const event = new Date();
let dateStr = event.toLocaleDateString(undefined);
console.log(dateStr); // 2023/7/24
言語コード指定
アメリカ
const event = new Date();
let dateStr = event.toLocaleDateString('en-US');
console.log(dateStr); // 7/24/2023
日本
const event = new Date();
let dateStr = event.toLocaleDateString('ja-JP');
console.log(dateStr); // 2023/7/24
オプションを指定
曜日を表示
const event = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric' };
let dateStr = event.toLocaleDateString('en-US', options);
console.log(dateStr); // Monday, 7/24/2023
//////////////////////
const event = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric' };
let dateStr = event.toLocaleDateString('ja-JP', options);
console.log(dateStr); // 2023/7/24月曜日
年月日を日本語表記に
const event = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
let dateStr = event.toLocaleDateString('ja-JP', options);
console.log(dateStr); // 2023年7月24日月曜日
曜日を省略形に
const event = new Date();
const options = { weekday: 'short', year: 'numeric', month: 'long', day: 'numeric' };
let dateStr = event.toLocaleDateString('ja-JP', options);
console.log(dateStr); // 2023年7月24日(月)
年を非表示に
const event = new Date();
const options = { weekday: 'short', month: 'long', day: 'numeric' };
let dateStr = event.toLocaleDateString('ja-JP', options);
console.log(dateStr); // 7月24日(月)
optionsから項目を無くせは非表示にできます。
言語指定しない
const event = new Date();
const options = { weekday: 'short', month: 'long', day: 'numeric' };
let dateStr = event.toLocaleDateString(undefined, options);
console.log(dateStr); // 7月24日(月)
言語指定をせず、undefinedにすると、ユーザー環境から言語を自動で決定するようです。
まとめ
必ずしも、自分が書き出したいフォーマットにできるとは限らないので、PHPのような仕様にして欲しいですね。
コメントを投稿する