NodeJS: Timezone

Config

When dateStrings: true, DATE, DATETIME and TIMESTAMPS are converted to ‘YYYY-MM-DD HH:mm:ss’ format. Thus, timezone setting does not affect the result.

const conn = mysql.createConnection({
        //dateStrings: true,  // ['DATE', 'DATETIME', 'TIMESTAMPS']
        dateStrings: ['DATE', 'DATETIME'],
        timezone: 'UTC',
        host: 'localhost',
        port: 3306,
        user: 'root',
        password: 'bigsecr3t',
        database: '<database-name>'
});

Using process.env.TZ

let tz = '2022-11-03T10:16:36.000Z';
let d = new Date(tz);
console.log(d.toString());
process.env.TZ = 'Asia/Jakarta';
console.log(d.toString());

Output:

Thu Nov 03 2022 10:16:36 GMT+0000 (Coordinated Universal Time)
Thu Nov 03 2022 17:16:36 GMT+0700 (Western Indonesia Time)

Using date.toLocaleString()

let tz = '2022-11-03T10:16:36.000Z';
let d = new Date(tz);
console.log(d.toString());
let e = d.toLocaleString('en-US', {
    timeZone: 'Asia/Jakarta'
});
console.log(e);

Output:

Thu Nov 03 2022 10:16:36 GMT+0000 (Coordinated Universal Time)
11/3/2022, 5:16:36 PM

Using bash/shell

env TZ="Asia/Jakarta" node index.js

References:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *