Use moment.js to change the timezone on a datetime stamp, without changing the time

Seth Wheeler :

I am migrating event data from an old SQL database to a new Mongo database, using NodeJS. However, whoever set up the SQL database created all of the dates for the events, made the times in PST/PDT, but the database believes they are in UTC time.

For Example: A date from the SQL database may be: 23-APR-10 which MomentJS shows as: 2010-04-23T21:00:00Z when 21:00:00 is the PST time.

Is it possible to use pure JavaScript/MomentJS/NodeJS or a different npm module to change the timezone on the DateTime string without modifying the time (i.e. 2010-04-23T21:00:00Z would become 2010-04-23T21:00:00-8:00)?

PS. Even though the SQL database only shows DD-MMM-YY but returns a DateTime string when I query it.

Anuj Pancholi :

Following the line of inquiry in the question comments, it seems your problem is that due to the timezone mishap, the timestamps stored in the db are stored without the timezone offset, and since your desired timezone is PST (UTC-8hours), the timestamps are 8 hours ahead, for instance, what should have been 2010-04-23T13:00:00Z has become 2010-04-23T21:00:00Z.

So what needs to be done here is that the utc offset for your desired timezone needs to be obtained and added to the date.

The offset in your case is known (-8 hours). However, we can fetch the correct offset of any desired timezone from the moment-timezone library.

const moment_timezone = require('moment-timezone');

//a sample timestamp you're getting from your db
const myDateObj = new Date("2010-04-23T21:00:00Z");

//timezone for PST as understood by moment-timezone
const myMomentTimezone = "America/Los_Angeles";

//offset for your timezone in milliseconds
const myTimezoneOffset = moment_timezone.tz(myMomentTimezone).utcOffset()*60000;

//perfom the correction
const getCorrectedDateObj = (givenDateObj) => new Date(givenDateObj.valueOf() + myTimezoneOffset);

console.log(getCorrectedDateObj(myDateObj));

You may notice that we are actually changing the timestamp, because the given timestamp and the requried timestamp are, due to the nature of the error, essentially different timestamps. Moment-timezone is only being used here to fetch the offset, it's not used to "convert" anything.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12410&siteId=1