Home
Blog
Products
Profile
Study
Collatz
© 2024 Oizumi Yuta

JavaScript で ISO 8601形式 から年月日時分秒を取得する

2024-09-14

1999-12-31T15:00:00.000Z という日付文字列の Z は、ISO 8601 形式で表された日時における「Zulu Time」の略で、協定世界時 (UTC: Coordinated Universal Time) を示している. これを日本時間で取得してみよう.

const date = new Date('1999-12-31T15:00:00.000Z');

// タイムゾーンを確認
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log('タイムゾーン: ', timeZone);

// JST に変換してから年・月・日を取得
const localYear = date.getFullYear(); // JST 基準の年を取得
const localMonth = date.getMonth() + 1; // JST 基準の月を取得 (0-based なので+1)
const localDay = date.getDate(); // JST 基準の日を取得

// JST に変換してから時・分・秒を取得
const localHours = date.getHours(); // JST 基準の時間を取得
const localMinutes = date.getMinutes(); // JST 基準の分を取得
const localSeconds = date.getSeconds(); // JST 基準の秒を取得

console.log('年: ', localYear);
console.log('月: ', localMonth);
console.log('日: ', localDay);
console.log('時: ', localHours);
console.log('分: ', localMinutes);
console.log('秒: ', localSeconds);

実行する.

$ node test.js
タイムゾーン:  Asia/Tokyo
年:  2000
月:  1
日:  1
時:  0
分:  0
秒:  0

タイムゾーンはユーザーのブラウザが設定されているタイムゾーンが表示されるため, 既に日本時間となっていることがわかる. すなわち特別な変換は必要ないのである.

ついでに UTC のまま取得する方法も記載しておこう.

const date = new Date('1999-12-31T15:00:00.000Z');

const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log('タイムゾーン: ', timeZone);

// UTC基準で年・月・日を取得
const utcYear = date.getUTCFullYear(); // UTC基準の年を取得
const utcMonth = date.getUTCMonth() + 1; // UTC基準の月を取得 (0-basedなので+1)
const utcDay = date.getUTCDate(); // UTC基準の日を取得

// UTC基準で時・分・秒を取得
const utcHours = date.getUTCHours(); // UTC基準の時間を取得
const utcMinutes = date.getUTCMinutes(); // UTC基準の分を取得
const utcSeconds = date.getUTCSeconds(); // UTC基準の秒を取得

console.log('年: ', utcYear);
console.log('月: ', utcMonth);
console.log('日: ', utcDay);
console.log('時: ', utcHours);
console.log('分: ', utcMinutes);
console.log('秒: ', utcSeconds);

実行する.

$ node test.js
タイムゾーン:  Asia/Tokyo
年:  1999
月:  12
日:  31
時:  15
分:  0
秒:  0

タイムゾーンは日本時間のまま UTC で取得できていることが確認できた.