This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
I've been dabbling with end-to-end testing time zones the other day and discovered that setting a browser time zone is reasonably straightforward in Playwright. Setting a browser time zone wasn't enough, though.
Testing my time zone aware UI also required setting a time zone in the running Node.js process to write correct assertions. How can you set time zones in Node.js?
By default, Node.js reuses the time zone set in your operating system. To access the default time zone, use JavaScript's Intl
object.
const date = new Date();
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
// 'Europe/Berlin'
console.log(date.toString());
// Sun Oct 20 2024 11:50:24 GMT+0200 (Central European Summer Time)
To change the used Node.js time zone, define the TZ
environment variable.
// Define `TZ` either when running the Node.js script
// -> $ TZ='America/New_York' node time-zone.js
//
// Or by setting `process.env`
// -> process.env.TZ = 'America/New_York';
const date = new Date();
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
// 'America/New_York'
console.log(date.toString());
// Sun Oct 20 2024 05:50:24 GMT-0400 (Eastern Daylight Time)
It's pretty cool that TZ
is evaluated at run-time so that you can mix and match time zones in your scripts.
const date = new Date();
// Set time zone to the Americas
process.env.TZ = 'America/New_York`;
console.log(date.toString());
// Sun Oct 20 2024 05:56:40 GMT-0400 (Eastern Daylight Time);
// Set time zone to Australia
process.env.TZ = 'Australia/Sydney';
console.log(date.toString());
// Sun Oct 20 2024 20:56:40 GMT+1100 (Australian Eastern Daylight Time);
// Delete time zone and fall back to Berlin, Germany
delete process.env.TZ;
console.log(date.toString());
// Sun Oct 20 2024 11:56:40 GMT+0200 (Central European Summer Time);
And if you don't want to set a default Node.js time zone but just display dates in different time zones, there are also multiple options to only change the date formating.
const date = new Date();
console.log(date.toLocaleString());
// 10/20/2024, 12:06:29 PM
console.log(date.toLocaleString('en-US', { timeZone: 'Australia/Sydney' }));
// 10/20/2024, 9:06:29 PM
console.log(
new Intl.DateTimeFormat('en-US', {
dateStyle: 'medium',
timeStyle: 'long',
timeZone: 'Australia/Sydney',
}).format(date),
);
// 20 Oct 2024, 21:06:29 GMT+11
I'm such an Intl
fan boy... Anyways — happy time traveling!
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Stefan Judis | Sciencx (2024-10-19T22:00:00+00:00) Set the default time zone in Node.js (#tilPost). Retrieved from https://www.scien.cx/2024/10/19/set-the-default-time-zone-in-node-js-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.