1

I am trying to set the timezone on the process.env object but it does not seem to work.

The following code is run as a JEST test, however it should still be relevant to node processes (right?).

If I set TZ to UTC, then the date I create is still my current timezone and not UTC. See below :

describe('Timezones', () => {
    it('should always be UTC', () => {

        process.env.TZ = 'UTC'

        let d = new Date();

        expect(d.getTimezoneOffset()).toBe(0); //ERROR!!! 120 minutes out... ie. Europe/Berlin where i am
    });
})
Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
  • I confirm it does not work also for me, but it does work if `TZ` is set outside node and before starting. (ie `env TZ='UTC' node`). Maybe the timezone is cached somewhere when starting node? – Thom Jul 30 '19 at 18:45

1 Answers1

1

If you set a time in process.env then you should fetch it from the process. So if you are in the Linux kernel you should run a shell script to fetch the date. Here is my solution for Linux.

process.env.TZ='UTC'
const execSync = require('child_process').execSync;
const output = execSync('date', { encoding: 'utf-8' }); 
console.log('UTC = '+output);

process.env.TZ='GMT'
const output2 = execSync('date', { encoding: 'utf-8' }); 
console.log('GMT = '+output2);
tuhin47
  • 5,172
  • 4
  • 19
  • 29
  • if you want to convert timezone in the code then try this https://stackoverflow.com/a/54127122/7499069 – tuhin47 Aug 02 '19 at 17:14