javascripttimezoneexceljs

ExcelJS - Date object is exported to Excel with the wrong time


I have a JavaScript Date object which is set to "Wed Mar 01 2023 12:54:19 GMT-0500 (Eastern Standard Time)".

When exporting this to Excel using ExcelJS, I end up with "3/1/2023 5:54:19 PM".

It is apparently converting the time portion to UTC, but I need to keep it in the local time.

Does anyone know why this is occuring or have a potential workaround?


Solution

  • To keep the date in local time, you can convert it to a string in the format you want before exporting it to Excel. Here's an example of how you can convert the date object to a string in the format "MM/DD/YYYY HH:MM:SS AM/PM" in Eastern Standard Time:

    const date = new Date("Wed Mar 01 2023 12:54:19 GMT-0500 (Eastern Standard Time)");
    const dateString = date.toLocaleString("en-US", {timeZone: "America/New_York"});
    

    The toLocaleString() method converts the date to a string using the specified format and timezone.