以下の環境でJavaScriptを実行し、日付を跨ぐタイムゾーン周りがどのように出力されるかまとめる
- Chrome: 112.0
- date-fns: 2.29.3
- date-fns-tz: 2.0.0
ChromeのタイムゾーンはAsia/Tokyo(+9)
javascript
import { parse, format } from "date-fns";
import { utcToZonedTime, zonedTimeToUtc } from "date-fns-tz";
console.log(new Date());
// Tue Apr 18 2023 19:15:38 GMT+0900 (日本標準時)
console.log(utcToZonedTime(new Date(), "Asia/Tokyo"));
// Tue Apr 18 2023 19:15:46 GMT+0900 (日本標準時)
console.log(utcToZonedTime("2023-04-18", "Asia/Tokyo"));
// Tue Apr 18 2023 00:00:00 GMT+0900 (日本標準時)
console.log(zonedTimeToUtc("2023-04-18", "Asia/Tokyo"));
// Tue Apr 18 2023 00:00:00 GMT+0900 (日本標準時)
console.log(parse("2023-04-18", "yyyy-MM-dd", new Date()));
// Tue Apr 18 2023 00:00:00 GMT+0900 (日本標準時)
console.log(format(new Date(), "yyyy-MM-dd"));
// 2023-04-18
ChromeのタイムゾーンはPacific/Kiritimati(+14)でAsia/Tokyoから翌日になるケース
javascript
import { parse, format } from "date-fns";
import { utcToZonedTime, zonedTimeToUtc } from "date-fns-tz";
console.log(new Date());
// Wed Apr 19 2023 00:18:42 GMT+1400 (GMT+14:00)
console.log(utcToZonedTime(new Date(), "Asia/Tokyo"));
// Tue Apr 18 2023 19:18:49 GMT+1400 (GMT+14:00)
console.log(utcToZonedTime("2023-04-18", "Asia/Tokyo"));
// Mon Apr 17 2023 19:00:00 GMT+1400 (GMT+14:00)
console.log(zonedTimeToUtc("2023-04-18", "Pacific/Kiritimati"));
// Tue Apr 18 2023 00:00:00 GMT+1400 (GMT+14:00)
console.log(parse("2023-04-18", "yyyy-MM-dd", new Date()));
// Tue Apr 18 2023 00:00:00 GMT+1400 (GMT+14:00)
console.log(format(new Date(), "yyyy-MM-dd"));
// 2023-04-19
ChromeのタイムゾーンはPacific/Pago_Pago(-11)でAsia/Tokyoから前日になるケース
javascript
import { parse, format } from "date-fns";
import { utcToZonedTime, zonedTimeToUtc } from "date-fns-tz";
console.log(new Date());
// Mon Apr 17 2023 23:27:14 GMT-1100 (サモア標準時)
console.log(utcToZonedTime(new Date(), "Asia/Tokyo"));
// Mon Apr 17 2023 23:27:48 GMT-1100 (サモア標準時)
console.log(utcToZonedTime("2023-04-18", "Asia/Tokyo"));
// Mon Apr 17 2023 04:00:00 GMT-1100 (サモア標準時)
console.log(zonedTimeToUtc("2023-04-18", "Pacific/Pago_Pago"));
// Tue Apr 18 2023 00:00:00 GMT-1100 (サモア標準時)
console.log(parse("2023-04-18", "yyyy-MM-dd", new Date()));
// Mon Apr 17 2023 04:00:00 GMT-1100 (サモア標準時)
console.log(format(new Date(), "yyyy-MM-dd"));
// 2023-04-18