Search code examples
javascriptnode.jsdate-fns

Date miscalculation on aws EBS server. It's running perfectly fine on local


There is always a miscalculation when deployed on aws server.

Context:

All the dates stored in mongoDB are in UTC format. And I want to convert the dates to IST before I export them in excel.

My code works perfectly fine on my local machine, but when deployed on server, it fails.

Here is an example that will help understand the issue.

const myDate = new Date('2022-12-21T18:41:18.384+00:00');

// The value of convertedDate should be 2022/12/21
// But, it for some reason returns - 2022/12/22
const convertedDate = myDate.toLocaleDateString('en-GB'); 

I also tried to user external library date-fns to handle the issue. Following is the sample code:

const zonedDate = utcToZonedTime(myDate, 'Asia/Kolkata');

// this is also - 2022/12/22
const convertedDate = formatInTimeZone(zonedDate, 'Asia/Kolkata', 'yyyy-MM-dd');
);

Another variation for date-fns that I tried was:

const zonedDate = utcToZonedTime(
      new Date(myDate.valueOf() + myDate.getTimezoneOffset() * 60 * 1000),
      'Asia/Kolkata',
);

// this is also - 2022/12/22
const convertedDate = formatInTimeZone(zonedDate, 'Asia/Kolkata', 'yyyy-MM-dd');

Please note that locally, everything works perfectly fine.


Solution

  • I also tried to use external library date-fns to handle the issue.

    It seems you converted back-and-forth, or even converted twice (for double the timezone offset?). You should not need to use utcToZonedTime at all. Just pass your original myDate timestamp into formatInTimeZone:

     const convertedDate = formatInTimeZone(myDate, 'Asia/Kolkata', 'yyyy-MM-dd');
    

    locally, everything works perfectly fine

    Change your system timezone to be that of the server (most likely UTC) and you should be able to reproduce the issue. For node.js, start it with the TZ environment variable.