- 1 year ago
Solution for process.env.TZ = 'UTC' in Node for Windows?
In Node.js, the process.env.TZ = 'UTC'
statement sets the time zone of the current process to UTC. However, on Windows systems, this approach may not work as expected due to the underlying operating system's time zone handling.
To set the time zone to UTC in Node.js on Windows, you can use the moment-timezone
library. Follow these steps:
Install the
moment-timezone
library using the following command:shellnpm install moment-timezone
In your Node.js script, require the
moment-timezone
module:javascriptconst moment = require('moment-timezone');
Set the time zone to UTC using the
moment.tz.setDefault()
method:javascriptmoment.tz.setDefault('UTC');
This will configure the default time zone for the moment library to UTC.
Use the moment library for date and time operations in your script. For example:
javascriptconst currentDateTime = moment().format('YYYY-MM-DD HH:mm:ss');
console.log(currentDateTime);
The
moment()
function will now return dates and times in UTC.
By using the moment-timezone
library and setting the default time zone to UTC, you can achieve the desired behavior of working with UTC time in your Node.js script on Windows.