Reputation: 651
Hi I'm using the moment library in node.js and setting the timezone. However, even after setting the timezone, I'm still getting the wrong date when I am console logging (it's a day ahead). Here is my sample code and output below.
Code:
const moment = require('moment-timezone');
const log4js = require('log4js');
let logger = log4js.getLogger();
logger.level ='debug'
let date1 = moment().tz("America/New_York").toDate()
logger.debug(date1)
Output:
[2019-02-13T21:09:48.019] [DEBUG] default - 2019-02-14T02:09:48.019Z
Notice how the date is a day ahead of today's actual date.
Upvotes: 0
Views: 332
Reputation: 3321
It's not randomly ahead, it's UTC, which is what JavaScript's native Date
handles (and this is what moment's .toDate
provides):
const now = moment();
const tz1 = 'America/New_York';
const tz2 = 'Africa/Nairobi';
// false: toDate provides a *copy* of the underlying native Date object
console.log(now.tz(tz1).toDate() === now.tz(tz2).toDate());
// true despite not being the same TZ: the underlying native Date is UTC-based
console.log(now.tz(tz1).toDate().toString() === now.tz(tz2).toDate().toString());
Upvotes: 1