JavaScript

Date.prototype.toLocaleDateString() メソッド

 編集:2022.12.02 by T.A.

[Edge]。→

Date の「日付」部を表す、言語特有の慣習による文字列を返します。

構文
Date.toLocaleDateString([locales[, options]])
Date Date
locales ¶文字列、文字列の配列。例: "ja-JP"、"en-US"、"en-GB"、"ko-KR"、['ban', 'id']。大文字小文字の区別はないようです。
options ¶オブジェクト。
weekday
値:文字列: long、showrt、?
year
値:文字列: numeric、?
month
値:文字列: long、short、?
day
値:文字列: numeric、?

mdn: locales 引数と options 引数をサポートしているブラウザーは、ブラウザーの実装状況 セクションを確認してください。機能が使用できるかどうかは、locales 引数と options 引数がサポートされているか確認するで確認してください。

mdn: 日時のそれぞれの部分ののプロパティにおける既定値は、undefinedです。ただし、weekday、 year、month、day プロパティがすべて undefined のときは、year、month、day は "numeric" とみなされます。

返り値

「日付」部を表す、言語特有の慣習による文字列。

性能/mdn

大量の日付を書式化する場合は、Intl.DateTimeFormat オブジェクトを生成してその format プロパティで提供される関数を使用したほうが得策です。

/mdn

ロケールを指定しない基本的な使い方では、既定のロケールと既定のオプションによる書式の文字列が返されます。

var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));

// toLocaleDateString() に引数を与えなければ実装に依存し、既定のロケールとタイムゾーンを返す
D=date.toLocaleDateString(); //="12/11/2012"。アメリカ、ロサンゼルスのタイムゾーンの en-US ロケールで実行した場合
locales の使用/mdn

この例では、国ごとに異なる日付書式を示します。アプリケーションのユーザー インターフェイスで使用されている言語の書式を得るには、locales 引数でその言語(あるいはフォールバック先の言語)を指定してください。

var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// 以下の書式はその地域のタイムゾーンとロケールを想定。米国のアメリカ大陸/ロサンゼルス
// 米国英語は月-日-年の順
D=date.toLocaleDateString('en-US'); //="12/19/2012"

// 英国英語は日-月-年の順
D=date.toLocaleDateString('en-GB'); //="20/12/2012"

// 韓国は年-月-日の順
D=date.toLocaleDateString('ko-KR'); //="2012. 12. 20."

// Event for Persian, It's hard to manually convert date to Solar Hijri
D=date.toLocaleDateString('fa-IR'); //="۱۳۹۱/۹/۳۰"

// 多くのアラビア語圏ではアラビア数字
D=date.toLocaleDateString('ar-EG'); //="٢٠‏/١٢‏/٢٠١٢"

// 日本語では、アプリケーションは元号を用いることがある
// 2012 年は平成 24 年
D=date.toLocaleDateString('ja-JP-u-ca-japanese'); //="24/12/20"

// 対応していない可能性のある言語を要求した場合、例えば
// バリ語とし、フォールバック言語にインドネシア語を指定した場合
D=date.toLocaleDateString(['ban', 'id']); //="20/12/2012"
options の使用/mdn

toLocaleDateString() メソッドから得られる結果は、options 引数でカスタマイズできます。

var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// 曜日を加えて月とともに長い書式で表す
var options = { weekday:'long', year:'numeric', month:'long', day:'numeric' };
D=date.toLocaleDateString('de-DE', options); //="Donnerstag, 20. Dezember 2012"

// アプリケーションで UTC を用いてそれを示したい場合
options.timeZone = 'UTC';
options.timeZoneName = 'short';
D=date.toLocaleDateString('en-US', options); //="Thursday, December 20, 2012, GMT"
DA=new Date("2022-10-05");  //2020年10月5日。
D=DA.toLocaleDateString();        //=[string]:2020/10/5
D=DA.toLocaleDateString("ja-jp"); //=[string]:2020/10/5
D=DA.toLocaleDateString('en-US'); //=[string]:10/5/2020

テスト