Search code examples
javascriptdateherokutime

JavaScript Date time different once deployed to Heroku


Locally, everything is accurate by the minute. Once deployed to Heroku, the difference between the times are off by about 6 hours. I am not looking to convert Heroku time zone (would like it to remain UTC). I've tried everything from getTimezoneOffset() conversions to different date formats and I still end up with the same result. How can I have these 2 date times match each other and not be offset by hours when deployed? Why are they different, when formatted the exact same way?

// Used to calculate current date time

const currentDate = new Date();
// ^ Production - (2021-10-12T19:12:41.081Z)
const time = `${currentDate.getHours()}:${currentDate.getMinutes()}`;
const fullDate = `${currentDate.getMonth()}/${currentDate.getDate()}/${currentDate.getFullYear()}`;
const currentDateFormatted = new Date(`${fullDate} ${time}`);
// ^ Production - (2021-10-12T19:12:00.000Z)

const currentParsedDateToUTC = Date.parse(currentDateFormatted.toUTCString());

// Used to calculate an event date time

const eventDate = new Date(`${event.date} ${event.endTime}`); // same exact format as above
// ^ Production - (2021-10-12T13:12:00.000Z)
const eventParsedDateToUTC = Date.parse(eventDate.toUTCString());

const isExpired = (currentParsedDateToUTC > eventParsedDateToUTC); // works locally, but not in production

In this example, the event date and start time is identical to the current date time. How can I prevent them from being vastly different?


Solution

  • That is because the Heroku server is in a different timezone than yours, you can handle it by converting the time format from your frontend, I recommend you use moment.js for example in your frontend you can convert like this:

    npm install moment --save
    

    And then you can create a function just to change the format to display:

    const formatDatetime = (
      datetime = "N/A",
      format = 'LLL' // here is your format
    ) => {
      return moment(datetime).isValid()
        ? moment(datetime).format(format)
        : datetime;
    };