I’ll introduce sample code for how to use dayjs.tz() to support Time Zone in Day.js.
I wanted to handle Time Zone with Day.js, so I ran sample code to understand it.
const dayjs = require('dayjs');
dayjs.extend(require('dayjs/plugin/utc'));
dayjs.extend(require('dayjs/plugin/timezone'));
dayjs.tz.setDefault('Etc/GMT')
dayjs.tz('2021-06-01 09:12:34', 'Asia/Tokyo').format()
// '2021-06-01T09:12:34+09:00'
dayjs.tz('2021-06-01 09:12:34', 'Asia/Tokyo').toDate()
// 2021-06-01T00:12:34.000Z
/** Code verified by setting TZ default to JST **/
dayjs.tz.setDefault('Asia/Tokyo')
dayjs.tz('2021-06-01 09:12:34').format()
// '2021-06-01T09:12:34+09:00'
dayjs.tz('2021-06-01 09:12:34').toDate()
// 2021-06-01T00:12:34.000Z
dayjs.tz('2021-06-01 09:12:34', 'Asia/Tokyo').format()
// '2021-06-01T09:12:34+09:00'
dayjs.tz('2021-06-01 09:12:34', 'Asia/Tokyo').toDate()
// 2021-06-01T00:12:34.000Z
const dayjs = require('dayjs');
dayjs.extend(require('dayjs/plugin/utc'));
dayjs.extend(require('dayjs/plugin/timezone'));
dayjs.tz.setDefault('Etc/GMT')
dayjs.tz('2021-06-01 09:12:34').tz('Asia/Tokyo').format()
// '2021-06-01T18:12:34+09:00'
dayjs.tz('2021-06-01 09:12:34').tz('Asia/Tokyo').toDate()
// 2021-06-01T09:12:34.000Z
When you want to consider timezone, using dayjs().tz(String) will cause bugs, so make sure to always use dayjs.tz().
const dayjs = require('dayjs');
dayjs.extend(require('dayjs/plugin/utc'));
dayjs.extend(require('dayjs/plugin/timezone'));
dayjs.tz.setDefault('Etc/GMT')
dayjs('2021-06-01 09:12:34').tz('Asia/Tokyo').format()
// '2021-06-01T09:12:34+09:00'
dayjs('2021-06-01 09:12:34').tz('Asia/Tokyo').toDate()
// 2021-06-01T00:12:34.000Z
dayjs('2021-06-01 09:12:34').tz('America/New_York').format()
// '2021-05-31T20:12:34-04:00'
dayjs('2021-06-01 09:12:34').tz('America/New_York').toDate()
// 2021-06-01T00:12:34.000Z
That’s all from the Gemba.