Date.prototype.getTime()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
試してみましょう
const moonLanding = new Date("July 20, 69 20:17:40 GMT+00:00"); // Jan 1, 1970, 00:00:00.000 GMT からの経過秒数 console.log(moonLanding.getTime()); // 予想される結果: -14182940000
構文
js
getTime()
引数
なし。
返値
解説
例
getTime() を使って日付をコピーする
同一の time 値を持つ date オブジェクトを構築します。
js
// month は 0 を基点とするため、birthday は 1995 年 1 月 10 日になります const birthday = new Date(1994, 12, 10); const copy = new Date(); copy.setTime(birthday.getTime());
実行時間を計測する
新たに生成された Date
オブジェクトでの、続く 2 個の getTime()
の結果を減算して、これらの呼び出しと呼び出しの間の時間を得ます。これは、何らかの命令の実行時間を計測するために使用できます。不要な Date
オブジェクトのインスタンス化を避けるため、Date.now()
も参照してください。
js
let end, start; start = new Date(); for (let i = 0; i < 1000; i++) { Math.sqrt(i); } end = new Date(); console.log(`Operation took ${end.getTime() - start.getTime()} msec`);
メモ: パフォーマンス API の高解像度時刻機能に対応しているブラウザーでは、 Performance.now()
を使用すると、 Date.now()
よりも信頼性が高く正確な経過時間を測定できます。
仕様書
Specification |
---|
ECMAScript® 2026 Language Specification # sec-date.prototype.gettime |