Day.js Time Zone Support Sample Code: How to Use dayjs.tz()

Tadashi Shigeoka ·  Tue, June 29, 2021

I’ll introduce sample code for how to use dayjs.tz() to support Time Zone in Day.js.

Day.js

Background: Want to Handle Time Zone with Day.js

I wanted to handle Time Zone with Day.js, so I ran sample code to understand it.

Day.js Time Zone Support Sample Code

Example usage of dayjs.tz(…, String)

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

Example usage of dayjs.tz().tz(String)

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

Example usage of dayjs().tz(String)

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.