Are references to Date object inside a map function carried over?

I am running into a weird issue where the dates in a function I have are being written to objects (and then stored) are having some side effects.

const normalizedEntries = allEntries.map((item) => {
  const dateObj = new Date(item.timestamp * 1000);
  const groupedDate = new Date(item.timestamp * 1000);
  groupedDate.setHours(0, 0, 0, 0);
  console.log(dateObj);
  console.log(groupedDate);
  const normalizedEntry: NormalizedEntry = {
    sites: item.sites,
    date: dateObj.toISOString(),
    groupedDate: groupedDate.toISOString(),
  };
  console.log(normalizedEntry);
  return normalizedEntry;
});

All I am trying to do in this function is take in an object that has a timestamp and a number (the sites field) and produce this new typed object NormalizedEntry which you can see has the original date, the sites (number) and a grouped date (which is just the day but with the time set to zero so I can group multiple objects later in redux).

Within the first two passes of the loop (for now I am working with a small set – 300, of test data) the data begins to get out of whack and I don’t understand why. Is there something going on with the references of the dates? Or perhaps something about dates I do not understand yet? Below is the output of those console logs from above

// iteration one
Wed Jan 20 2021 17:16:49 GMT-0500 (Eastern Standard Time)
Wed Jan 20 2021 00:00:00 GMT-0500 (Eastern Standard Time)
{sites: 26, date: "2021-01-20T22:16:49.000Z", groupedDate: "2021-01-20T05:00:00.000Z"}
// iteration two
Wed Jan 20 2021 20:27:58 GMT-0500 (Eastern Standard Time)
Wed Jan 20 2021 00:00:00 GMT-0500 (Eastern Standard Time)
{sites: 41, date: "2021-01-21T01:27:58.000Z", groupedDate: "2021-01-20T05:00:00.000Z"}

As you can see the console.log(dadte) prints out the correct thing in the second iteration but for some reason when setting it to the object below it says it’s on the 21st versus the 20th which it clearly is 5 lines above. This is in turn throwing all of my data out of whack.

EDIT:
Now trying to resolve it being a timezone issue as pointed out from below but this is still not resolving the issue:

const normalizedEntries = allEntries.map((item, idx) => {
  let originDate = new Date(item.timestamp * 1000);

  const timezoneDifference = originDate.getTimezoneOffset() / 60;
  const correctedDate = new Date(
    originDate.setHours(originDate.getHours() + timezoneDifference, 0, 0, 0)
  );

  let groupedDate = correctedDate;
  groupedDate.setHours(0, 0, 0, 0);

  console.log(originDate.toString());
  console.log(groupedDate.toString());
  const normalizedEntry: NormalizedAcquisition = {
    sites: item.sites,
    date: originDate.toISOString(),
    groupedDate: groupedDate.toISOString(),
  };
  return normalizedEntry;
});

1 thought on “Are references to Date object inside a map function carried over?”

Leave a Comment