=================================================================================
Date()
現在時刻や特定の日時の情報を取得。
1. 現在時刻のタイムスタンプ(ミリ秒)を取得する
const now = new Date();
const timestamp = now.getTime(); // または Date.now();
console.log(timestamp); // 例: 1735728000000 (ミリ秒)
2. 時・分・秒などの特定の部分を取得する
const now = new Date();
const hours = now.getHours(); // 現在の時 (0-23)
const minutes = now.getMinutes(); // 現在の分 (0-59)
const seconds = now.getSeconds(); // 現在の秒 (0-59)
const year = now.getFullYear(); // 現在の年
const month = now.getMonth(); // 現在の月 (0-11)
const day = now.getDate(); // 現在の日 (1-31)
console.log(`${year}年${month+1}月${day}日 ${hours}時${minutes}分${seconds}秒`);
3. 地域形式の文字列で取得する
const now = new Date();
const formattedTime = now.toLocaleString();
console.log(formattedTime); // 例: "2025/1/1 10:30:00"
=====================================================================================
Date.now()
1970年1月1日0時0分0秒(UTC)からの経過ミリ秒を取得する。オブジェクト生成が不要。
パフォーマンスが重要な場合に推奨。主に経過時間の測定などに使用。
1. 実行時間の計測に使う
const startTime = Date.now();
// 何らかの処理...
let sum = 0;
for(let i=0; i<1000000; i++){ sum += i; }
const endTime = Date.now();
const duration = endTime - startTime;
console.log(`処理時間: ${duration}ミリ秒`);
オブジェクト生成が不要なため、パフォーマンスが重要な場合に推奨され、主に経過時間の測定などに使われます。
=====================================================================================