Search code examples
javascriptdate-fns

Date-fns addDays function does not add correct number of days


I am currently working with the date-fns library in JavaScript and I am encountering an unexpected behavior when trying to add days to a date. The issue arises in the createComparisonChart function, where the calculateDataForPeriod function is called in two different scopes.

export function createComparisonChart(data) {
  let comparisonChart;

  const dateNow = new Date();

  const date7DaysAgo = dateFns.subDays(dateNow, 7);
  let comparisonDays = 7;
  let currentPeriodData = calculateDataForPeriod(
    data,
    date7DaysAgo,
    comparisonDays
  ); //period is calculated correctly here

  const comparisonButton = document.getElementById("comparison-button");
  comparisonButton.addEventListener("click", () => {
    const currentStartDateInput = document.getElementById("current-start-date");
    const comparisonDaysInput = document.getElementById("comparison-days");

    const currentStartDate = currentStartDateInput.value
      ? new Date(currentStartDateInput.value)
      : date7DaysAgo;
    comparisonDays = comparisonDaysInput.value
      ? comparisonDaysInput.value
      : comparisonDays;

    currentPeriodData = calculateDataForPeriod(
      data,
      currentStartDate,
      comparisonDays
    ); //period is calculated incorrectly here

    //comparison chart generation code
  });

 //comparison chart generation code
}

function calculateDataForPeriod(data, startDate, comparisonDays) {
  startDate = new Date(startDate);
  const endDate = dateFns.addDays(startDate, comparisonDays);
  //const endDate = new Date(startDate.getTime() + comparisonDays * 24 * 60 * 60 * 1000);

  //period data calculation code
}

In the first scope, the period is calculated correctly. However, when I click the comparison-button (event listener scope), the period is calculated incorrectly.

For instance, when I try to add 7 days to 23/05/2024, it returns 23/12/2024, 16/05/2024 -> 14/10/2024, 30/05/2024 -> 03/05/2025. When the comparisonDays becomes a two-digit number, the results are even more unexpected. For example, adding 10 days to 30/05/2024 returns 27/07/2032.

This behavior persists even when both of the variables comparisonDays and date7DaysAgo are passed the same in both of the scopes (not from the HTML elements in the second scope). I am using version 3.6.0 of the date-fns library.

I've looked up similar problems but all of them have very small time differences and the reason is the timezone or months being 0 based in JS. I don't see how any of them could be the problem in this case.

new Date(startDate.getTime() + comparisonDays * 24 * 60 * 60 * 1000) works as expected.

As I am new to JavaScript, I'm pretty sure this is not a bug and I'm missing something. Any insights would be greatly appreciated.


Solution

  • Turns out getElementById returns string type and I had to cast it to int. Casting comparisonDaysInput.value to int fixed the issue.