javascriptmomentjsmoment-timezone

Using moment.js Timezone to set starting timezone and converting to other timezones


I'm following an example from https://www.alex-arriaga.com/how-to-set-moment-js-timezone-when-creating-a-date/ but not getting the results I'm expecting. My startDateAndTimeString has the time set to 08:00 and I set the timezone to Mexico_City which is in CST. Then I'm trying to convert to New_York (EST) and Los_Angeles (PST) time.

I would expect if the starting time is 08:00 CST then it would be 09:00 EST and 06:00 PST but I'm seeing 05:00 PST and 08:00 EST. Locally, I'm in EST which would make sense if I wasn't setting the starting time to CST. Can I not set the starting time to CST when I'm in EST ?

var startDateAndTimeString = '2023-03-05 08:00:00';

// CST
var startDateAndTime = moment(startDateAndTimeString).tz('America/Mexico_City');

function formatDateToAnotherTimezone(anotherTimezone, startDateAndTime) {
 return moment(startDateAndTime).tz(anotherTimezone).format('ha z');
}


var est = formatDateToAnotherTimezone('America/New_York',startDateAndTime);
var pst = formatDateToAnotherTimezone('America/Los_Angeles',startDateAndTime);

console.log(est)
console.log(pst)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>


Solution

  • I think that is not the correct way to use moment.tz

    To make it easier, I am printing out the GMT time represented by startDateAndTime in the Mexico timezone.

    You can see that the first console.log prints the wrong answer.

    But when we call moment.tz correctly, the second console.log prints the right answer.

    The subsequent adjustments use the correct value of startDateAndTime.

    var startDateAndTimeString = '2023-03-05 08:00:00';
    
    // CST
    var wrongStartDateAndTime = moment(startDateAndTimeString).tz('America/Mexico_City');
    console.log("wrongStartDateAndTime",wrongStartDateAndTime)
    
    startDateAndTime = moment.tz(startDateAndTimeString,'America/Mexico_City');
    console.log("When we instead use moment.tz correctly:")
    console.log("startDateAndTime",startDateAndTime)
    
    
    function formatDateToAnotherTimezone(anotherTimezone, startDateAndTime) {
      return moment(startDateAndTime).tz(anotherTimezone).format('ha z');
    }
    
    
    var est = formatDateToAnotherTimezone('America/New_York', startDateAndTime);
    var pst = formatDateToAnotherTimezone('America/Los_Angeles', startDateAndTime);
    
    console.log(est)
    console.log(pst)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>