JavaScript/Date

出典: フリー教科書『ウィキブックス(Wikibooks)』


Dateオブジェクト[編集]

Dateオブジェクトは日付を扱うためのオブジェクトです[1]。 次の様に書くことで、現在時を取得する事が出来る。

const d = new Date();

この後、toStringメソッド等を利用して日付を文字列に変換して人可読な形式にしていく。

日付を指定してオブジェクトを作成したい場合には、次の様に日付を指定していく。

const d = new Date(2007, 10, 21);	// 2007年11月21日のオブジェクトを作成 
const d = new Date(2007, 10, 21, 8, 13, 21);	// 2007年11月21日 8:13:21のオブジェクトを作成
const d = new Date(99, 6);	// 1999年7の月のオブジェクトを作成

(年を0~99で指定した場合は19xx年を設定するため、西暦0~99年を指定したいときはsetFullYearを利用する。)

Dateオブジェクトには次の問題点があります。

まず、Dateオブジェクトは有限の範囲の日付しか扱えません。 この範囲は、UNIX時間にNumber.MAX_SAFE_INTEGER(2 ** 53 - 1)ミリ秒足したものではない事に注意してください。 ECMA-262 は、Dateオブジェクトで表すことができる時刻の範囲はエポックから前後 ±100,000,000 (1億) 日、紀元前271821年4月20日から紀元275760年9月13日)と定義しています[2]

また、現行の協定世界時 (UTC) において、世界時のUT1との差を調整するため、閏秒(うるうびょう)が挿入されますが、ECMA標準では挿入されない仕様となっています。そのため、秒単位では違いがある可能性があります。

静的メソッド[編集]

Date.parse(string)[編集]

文字列を解析して、1970年1月1日からの経過時間をミリ秒単位で返します。

解析した結果はDateオブジェクトで返されるわけではないので、Dateオブジェクトへの変換は次の様に行う。

const d = new Date();
d.setTime(Date.parse("2001/9/11"));

RFC2822 または ISO 8601 の日付を表す文字列であればECMAScriptの仕様に従う限りパースできます。それ以外の書式は実装に依存しています[3]

Date.UTC (year, month [, date [, hours [, minutes [, seconds [, ms]]]]])[編集]

1970年1月1日からの経過時間をミリ秒単位で返します。

const d = new Date();
d.setTime(Date.UTC(2001, 9, 11));

ローカル時間取得のメソッド[編集]

Date.prototype.getFullYear()[編集]

地方時の西暦の年を返します。よく似たメソッドにDate.prototype.getYear()[4]がありますが、これは1900年からの年数を返すので注意が必要です。

Date.prototype.getMonth()[編集]

地方時の月を返します。返される値は0~11の範囲の値を取り、実際の月数より1少ない。 つまり1月の場合は0、2月の場合は1が返ります。月名を列挙した配列の添字とおぼえて下さい。

const d = new Date();
console.log(d); // Mon Jun 28 2021 08:06:50 GMT+0900 (日本標準時)
console.log(d.getMonth()) // 5
console.log("Jab Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ")[d.getMonth()]); // Jun

Date.prototype.getDate()[編集]

地方時の日付(1~31)を取得する。

Date.prototype.getDay()[編集]

地方時の曜日を取得する。Date.prototype.getDay() メソッドは、地方時に基づき、指定された日付の「曜日」を返します。

Date.prototype.getHours()[編集]

地方時の時間(0~23)を取得する。

Date.prototype.getSeconds()[編集]

地方時の分(0~59)を取得する。

Date.prototype.getMinutes()[編集]

地方時の秒(0~59)を取得する。

Date.prototype.getMilliseconds()[編集]

地方時の1秒未満(ミリ秒単位)を取得する。

Date.prototype.setFullYear(year [, month [, date]])[編集]

地方時の年を設定する。

Date.prototype.setMonth(month [, date])[編集]

地方時の月(0-11)を設定する。

Date.prototype.setDate(date)[編集]

地方時の日を設定する。

Date.prototype.setHours(hour [, min [, sec [, ms]]])[編集]

地方時の時を設定する。

Date.prototype.setMinutes(min [, sec [, ms]])[編集]

地方時の分を設定する。

Date.prototype.setSeconds(sec [, ms])[編集]

地方時の秒を設定する。

Date.prototype.setMilliseconds(ms)[編集]

地方時の1秒未満(ミリ秒単位)を設定する。

協定世界時のメソッド[編集]

ここまでのメソッドは、地方時を対象にしていましたが、国や地域によって違うタイムゾーンの影響を廃するため協定世界時(Coordinated Universal Time)を対象とするメソッドが用意されています。

Date.prototype.getUTCFullYear()[編集]

協定世界時での年を取得する。

console.log(new Date().getUTCFullYear()); // 2021

Date.prototype.getUTCMonth()[編集]

協定世界時での月(0-11)を取得する。

console.log(new Date().getUTCMonth()); // 5

Date.prototype.getUTCDate()[編集]

協定世界時での日付を取得する(1-31)。

console.log(new Date().getUTCDate()); // 27

Date.prototype.getUTCDay()[編集]

協定世界時での週を取得する。0が日曜日

console.log("日月火水木金土"[new Date().getUTCDay()]); // 日

Date.prototype.getUTCMinutes()[編集]

協定世界時での分を取得する。

console.log(new Date().getUTCMinutes()); // 49

Date.prototype.getUTCSeconds()[編集]

協定世界時での秒を取得する。

console.log(new Date().getUTCSeconds()); // 15

Date.prototype.getUTCMilliseconds()[編集]

協定世界時での1秒未満をミリ秒単位に取得する。

console.log(new Date().getUTCMilliseconds()); // 555

Date.prototype.setUTCFullYear(year [, month [, date]])[編集]

協定世界時での年を設定します。

Date.prototype.setUTCMonth(month [, date])[編集]

協定世界時での月を設定します。

Date.prototype.setUTCDate(date)[編集]

協定世界時での日を設定します。

Date.prototype.setUTCHours(hour [, min [, sec [, ms]]])[編集]

協定世界時での時間を設定します。

Date.prototype.setUTCMinutes(min [, sec [, ms]])[編集]

協定世界時での分を設定します。

Date.prototype.setUTCSeconds(sec [, ms])[編集]

協定世界時での秒を設定します。

Date.prototype.setUTCMilliseconds(ms)[編集]

協定世界時でのミリ秒を設定します。

時間文字列化メソッド[編集]

これらのメソッドは時間を人可読な文字列にします。

Date.prototype.toString()[編集]

Dateオブジェクトの日付時刻とタイムゾーンを文字列で返します。 どの様な値を返すのかは仕様に定められておらす、実装によって微妙に値は異なる。 ES2018/ES9までは、 Date.prototype.toString が返す文字列の書式は実装に依存していました[5]。 d.valeuOf() が 1000 で割り切れるような Date オブジェクト d については、Date.parse(d.toString()) === d.valueOf() が真となります。

console.log((new Date()).toString());

"Mon Jun 28 2021 07:36:27 GMT+0900 (日本標準時)" の様な文字列が返ります。

Date.prototype.toDateString()[編集]

Dateオブジェクトの日付をを文字列で返します。

console.log((new Date()).toDateString());

"Mon Jun 28 2021" の様な文字列が返ります。

Date.prototype.toTimeString()[編集]

Dateオブジェクトの時刻とタイムゾーンを文字列で返します。

console.log((new Date()).toTimeString());

"08:58:39 GMT+0900 (日本標準時)" の様な文字列が返ります。

Date.prototype.toLocaleString([locales[, options]])[編集]

Dateオブジェクトの日付時刻とタイムゾーンを言語と国(や地域)に合わせた日時の文字列を返します。 {{See also| Intl.DateTimeFormat()

const d = new Date();
console.log(d.toLocaleString('en-US', { timeZone: 'UTC' })); // 6/28/2021, 12:09:43 AM
console.log(d.toLocaleString('en-GB', { timeZone: 'UTC' })); // 28/06/2021, 00:09:43
console.log(d.toLocaleString('ja-JP', { timeZone: 'UTC' })); // 2021/6/28 0:09:43
console.log(d.toLocaleString('ja-JP-u-ca-japanese', {era: 'long', timeZone: 'UTC' })); // 令和3年6月28日 0:09:43
const d2 = new Date(1600, 9, 21)
console.log(d2.toLocaleString('ja-JP-u-ca-japanese', {era: 'long', timeZone: 'UTC' })); // 慶長5年10月20日 14:41:01

の様な文字列が返ります。

Date.prototype.toLocaleDateString()[編集]

Dateオブジェクトの日付時刻とタイムゾーンを言語と国(や地域)に合わせた日付の文字列を返します。

const d = new Date();
console.log(d.toLocaleDateString('en-US', { timeZone: 'UTC' })); // 6/28/2021
console.log(d.toLocaleDateString('en-GB', { timeZone: 'UTC' })); // 28/06/2021
console.log(d.toLocaleDateString('ja-JP', { timeZone: 'UTC' })); // 2021/6/28
console.log(d.toLocaleDateString('ja-JP-u-ca-japanese', {era: 'long', timeZone: 'UTC' })); // 令和3年6月28日
const d2 = new Date(1600, 9, 21)
console.log(d2.toLocaleDateString('ja-JP-u-ca-japanese', {era: 'long', timeZone: 'UTC' })); // 慶長5年10月20日

Date.prototype.toLocaleTimeString()[編集]

Dateオブジェクトの日付時刻とタイムゾーンを言語と国(や地域)に合わせた時刻の文字列を返します。

const d = new Date();
console.log(d.toLocaleTimeString('en-US', { timeZone: 'UTC' })); // 12:27:37 AM
console.log(d.toLocaleTimeString('en-GB', { timeZone: 'UTC' })); // 00:27:37
console.log(d.toLocaleTimeString('ja-JP', { timeZone: 'UTC' })); // 0:27:37
console.log(d.toLocaleTimeString('ja-JP-u-ca-japanese', {era: 'long', timeZone: 'UTC' })); // 令和 0:27:37
const d2 = new Date(1600, 9, 21)
console.log(d2.toLocaleTimeString('ja-JP-u-ca-japanese', {era: 'long', timeZone: 'UTC' })); // 慶長 14:41:01

Date.prototype.toUTCString()[編集]

Dateオブジェクトの日付時刻とタイムゾーンを文字列を協定世界時で返します。

const d = new Date();
console.log(d.toUTCString());

"Mon, 28 Jun 2021 00:32:41 GMT" の様な文字列が返ります。

その他[編集]

Date.prototype.valueOf()[編集]

1970年1月1日0時0分UTC(いわゆるエポック)からの通算ミリ秒単位で取得する。 これは一般的にはUNIX時間と言われる時間でUnix内部での時間管理の仕組みと合わせてある[6]

Date.prototype.getTime()[編集]

動作はvalueOfメソッドと同じであるが歴史的経緯からこちらの方の使用を推奨する。

Date.prototype.setTime(time)[編集]

1970年1月1日0時0分からの経過時間(ミリ秒)で時間を設定する。

Date.prototype.getTimezoneOffset()[編集]

現在の環境とUTC標準との時間差を分で返します。 日本の場合はロンドンからは9時間前倒しなので、9(時間)×60(分)で「-540(分)」が返ります。

資料[編集]

Dateオブジェクトの各種メソッドの変換結果を調査しました。

const a = [],date = new Date(2021,5,22), ua=navigator.userAgent;
a.push(`==${ua}===
{| class="wikitable"
|- align="left"
! メソッド !! 結果`)
for (const p in Object.getOwnPropertyDescriptors(Date.prototype))
    if (typeof Date.prototype[p] === "function" && /^to/.test(p))
        a.push(`|-\n! ${p}()\n| ${date[p]()}`)
a.push(`|-\n!toLocaleString('ja-JP-u-ca-japanese', {era: 'long'})()\n| ${date.toLocaleString('ja-JP-u-ca-japanese', {era: 'long'})}`)
a.push`|}`

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36=[編集]

メソッド 結果
toDateString() Tue Jun 22 2021
toGMTString() Mon, 21 Jun 2021 15:00:00 GMT
toISOString() 2021-06-21T15:00:00.000Z
toJSON() 2021-06-21T15:00:00.000Z
toLocaleDateString() 2021/6/22
toLocaleString() 2021/6/22 0:00:00
toLocaleTimeString() 0:00:00
toString() Tue Jun 22 2021 00:00:00 GMT+0900 (日本標準時)
toTimeString() 00:00:00 GMT+0900 (日本標準時)
toUTCString() Mon, 21 Jun 2021 15:00:00 GMT
toLocaleString('ja-JP-u-ca-japanese', {era: 'long'})() 令和3年6月22日 0:00:00

Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0=[編集]

メソッド 結果
toDateString() Tue Jun 22 2021
toGMTString() Mon, 21 Jun 2021 15:00:00 GMT
toISOString() 2021-06-21T15:00:00.000Z
toJSON() 2021-06-21T15:00:00.000Z
toLocaleDateString() 2021/6/22
toLocaleString() 2021/6/22 0:00:00
toLocaleTimeString() 0:00:00
toString() Tue Jun 22 2021 00:00:00 GMT+0900 (日本標準時)
toTimeString() 00:00:00 GMT+0900 (日本標準時)
toUTCString() Mon, 21 Jun 2021 15:00:00 GMT
toLocaleString('ja-JP-u-ca-japanese', {era: 'long'})() 令和3年6月22日 0:00:00

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.59=[編集]

メソッド 結果
toDateString() Tue Jun 22 2021
toGMTString() Mon, 21 Jun 2021 15:00:00 GMT
toISOString() 2021-06-21T15:00:00.000Z
toJSON() 2021-06-21T15:00:00.000Z
toLocaleDateString() 2021/6/22
toLocaleString() 2021/6/22 0:00:00
toLocaleTimeString() 0:00:00
toString() Tue Jun 22 2021 00:00:00 GMT+0900 (日本標準時)
toTimeString() 00:00:00 GMT+0900 (日本標準時)
toUTCString() Mon, 21 Jun 2021 15:00:00 GMT
toLocaleString('ja-JP-u-ca-japanese', {era: 'long'})() 令和3年6月22日 0:00:00

脚注[編集]

  1. ^ https://tc39.es/ecma262/#sec-date-objects 21.4 Date Objects
  2. ^ [ECMA-262::21.4.1.1 Time Values and Time Range]
  3. ^ [ECMA-262 21.4.1.15 Date Time String Format]
  4. ^ 非推奨
  5. ^ ECMA-262::21.4.4.41 Date.prototype.toString ()
  6. ^ ただしUNIX時間は秒区切りでミリ秒区切りではない