I am trying to use the moment.tz library however the dates keep changing in new timezones since the time is set at midnight (0:00:00). I would like the dates to be unchanged when changing timezones.
Essentially I have
const checkin = 2022-08-30T00:00:00.000Z <-- Date Object
console.log(moment.tz(checkin, 'YYYY-MM-DD HH:mm:ss', 'UTC') );
console.log(moment.tz(checkin, 'YYYY-MM-DD HH:mm:ss', 'America/Toronto') );
When I use the timezone America/Toronto, the date gets moved back a day since the time is midnight. This results in the following output:
Moment<2022-08-30T00:00:00Z>
Moment<2022-08-29T20:00:00-04:00>
My Goal is to have the moment function using time zone to reflect the same date (YYYY-MM-DD) as utc. The checkin date should not be changed based on timezone. Any Suggestions?
You can change the timezone and keep the same date and time values by setting the second parameter to true. Make sure this is really what you want to do, the moment object will now represent a different moment in time.
// Create date object
let checkin = new Date('2022-08-30T00:00:00.000Z');
// Convert to moment object
let checkinMoment = moment.tz(checkin, 'YYYY-MM-DD HH:mm:ss', 'UTC');
// Display
console.log(checkinMoment.format());
// Change timezone, keep date and time values the same (i.e. shift to
// a different moment in time
checkinMoment.tz('America/Toronto', true);
// Show same date and time but in different timezone
console.log(checkinMoment.format());
// Alternatively, parse a timestamp in the required zone
let d = '2022-08-30T00:00:00.000';
let torontoCheckin = moment.tz(d, "America/toronto");
console.log(torontoCheckin.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.34/moment-timezone-with-data-2012-2022.js"></script>