Date functions with leap years

I thought by using getTimezoneOffset leap years would be catered for

export const dateToDays = async (date: string): Promise<number | null> => {
  if (date === "") return null;
  const now: Date = new Date(date);
  const start: Date = new Date(now.getFullYear(), 0, 0);
  const diff =
    +now -
    +start +
    (start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000;
  const oneDay = 1000 * 60 * 60 * 24;
  const day = Math.floor(diff / oneDay);
  if (!day) return null;
  return Number(day);
};

but when I run a test for the 29th of Feb 1960 (not a leap year, there is only 28 days in Feb) I expected it to return null


test("Test Leap 1961", async () => {
  expect(await dateToDays("1961-02-29")).toEqual(null); // 61
});

there also isn’t 30 days in Feb 1960

test("Test Leap 1960", async () => {
  expect(await dateToDays("1960-02-30")).toEqual(null); // 60
});

How can I ensure the above 2 tests return null? or put another way how to make the function return null if a day that doesn’t exist is requested?

45 thoughts on “Date functions with leap years”

Leave a Comment