1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScript new Date(), date-fns, date-fns-tz周りの日付を跨ぐタイムゾーンの扱い

Last updated at Posted at 2023-04-19

以下の環境で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
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?