Reputation: 373
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.
Upvotes: 3
Views: 896
Reputation: 373
Anuj Pancholi's answer is correct, however; the old SQL database I'm using seems to have a lot of quirks, so I had to modify his answer to get my code working.
My Solution:
function getCorrectedDateObj(myDateObj){
const timezoneOffset = momentTimeZone.tz(timezone).utcOffset() * 60000;
const dt = new Date(myDateObj.valueOf() + timezoneOffset / 2);
dt.setHours(dt.getHours() + 12);
}
Upvotes: 0
Reputation: 1213
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.
Upvotes: 1