How to set timezone in Node.js?

Member

by dasia , in category: JavaScript , 2 years ago

How to set timezone in Node.js?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by brisa , 2 years ago

@dasia use process.env to set timezone in Node.js, code:


1
2
3
process.env.TZ = 'Europe/Helsinki'

console.log(new Date().toString())
by mathias.schinner , 8 months ago

@dasia 

To set the timezone in Node.js, you can use the 'moment-timezone' library. Here's how you can do it:


First, install the 'moment-timezone' library by running the following command in your terminal:

1
npm install moment-timezone


Then, in your Node.js file, import the 'moment-timezone' module and use it to set the timezone:

1
2
3
4
5
6
7
const moment = require('moment-timezone');

// Set the timezone
moment.tz.setDefault('America/New_York');

// Print the current date and time in the set timezone
console.log(moment().format());


In this example, we set the timezone to 'America/New_York' by using the moment.tz.setDefault() method. You can replace 'America/New_York' with the desired timezone identifier, which you can find from the Moment Timezone website (https://momentjs.com/timezone/).


After setting the timezone, you can use moment() to get the current date and time in the set timezone.