Search code examples
javascriptmomentjsmoment-timezone

Moment timezone: Local Timezone gets applied to parsed date but not on format()


Context: I have a server hosted on a VM in the cloud. When using just the moment library to initialize dates I always get a date which has +- some hours. After a quick research, I found the moment-timezone library which should solve this issue but I have some problems.

I have the following date: "transactionDate": "2020-08-25 18:30:00" which gets submitted.

My code now looks like this where moment is the moment-timezone library now:

  const momentTransactionDate = moment.tz(transactionDate, "YYYY-MM-DD HH:mm:ss", "Europe/Bucharest");

  const formattedTransactionDate = momentTransactionDate.format(
    "YYYY-MM-DD HH:mm:ss"
  );

This will output the following values:

    "momentTransactionDate": "2020-08-25T15:30:00.000Z",
    "formattedTransactionDate": "2020-08-25 18:30:00",

For testing, I'm just doing a request from Postman to the local server. Why is the momentTransactionDate 3 hours before, and why is the format() function formatting a different hour?

Could someone explain how this is working?


Solution

  • The momentTransactionDate object is specified to be in Bucharest time, so it will be three hours ahead of UTC time (in DST at the moment, https://www.timeanddate.com/time/zones/eest).

    I'm presuming that you've logged something like this:

    console.log( { momentTransactionDate: momentTransactionDate.toISOString(), formattedTransactionDate});
    

    toISOString() outputs the UTC time of the date, so this is exactly what we'd expect. 18:30 in Bucharest (at this time of year) corresponds to 15:30 UTC time.

    And to parse UTC dates we can use a timezone name of "UTC":

    const transactionDate = "2020-08-17 17:30:00";
    const momentTransactionDate = moment.tz(transactionDate, "YYYY-MM-DD HH:mm:ss", "UTC");
    
    const formattedTransactionDate = momentTransactionDate.format(
        "YYYY-MM-DD HH:mm:ss"
    );
    
    console.log("momentTransactionDate.toISOString():", momentTransactionDate.toISOString());
    console.log("formattedTransactionDate:", formattedTransactionDate); 
    <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.25/moment-timezone-with-data-10-year-range.js"></script>