malfoy
malfoy

Reputation: 80

Trying to check if the 2 dates are in the same week

I am using date-fns to check if the 2 dates are on the same week or not.

following the documentation If I do :

 const isSameWk = isSameWeek(
      new Date("2023-02-05"),
      new Date("2023-02-06"),
      { weekStartsOn: 0, locale: "en-GB" }
    );

If I do the above snippet it will say true which is correct but it throws the error that I need to use parseISO since the new beta v2

so using parseISO

this way 
     const isSameWk = isSameWeek(
      parseISO(new Date("2023-02-05")),
      parseISO(new Date("2016-02-06")),
      { weekStartsOn: 0, locale: "en-GB" }
    );

or 
 const isSameWk = isSameWeek(
      parseISO("2023-02-05"),
      parseISO(("2016-02-06")),
      { weekStartsOn: 0, locale: "en-GB" }
    );

would not throw the error but console logging just this parseISO("2023-02-05") gives me the correct but not in my locale and logging parseISO(new Date("2023-02-05")) would give invalid date

Stuck on this for a long time can't figure out where am I wrong at.

Upvotes: 0

Views: 707

Answers (1)

Peter Thoeny
Peter Thoeny

Reputation: 7616

Here is are native JavaScript Date functions, no need for an external library:

const getWeekNum = (date) => {
  const janFirst = new Date(date.getFullYear(), 0, 1);
  // Source: https://stackoverflow.com/a/27125580/3307678
  return Math.ceil((((date.getTime() - janFirst.getTime()) / 86400000) + janFirst.getDay() + 1) / 7);
}

const isSameWeek = (dateA, dateB) => {
  return getWeekNum(dateA) === getWeekNum(dateB);
}

const date1Str = '2023-02-05';
const date2Str = '2023-02-06';
const date3Str = '2023-02-12';
const dateSuffix = 'T00:00:00.000Z'; // or 'T00:00:00.000' for browserlocal time
const date1 = new Date(date1Str + dateSuffix);
const date2 = new Date(date2Str + dateSuffix);
const date3 = new Date(date3Str + dateSuffix);
console.log({
  'date1': date1,
  'date2': date2,
  'date3': date3,
  'getWeekNum(date1)': getWeekNum(date1),
  'getWeekNum(date2)': getWeekNum(date2),
  'getWeekNum(date3)': getWeekNum(date3),
  'isSameWeek(date1, date2)': isSameWeek(date1, date2),
  'isSameWeek(date1, date3)': isSameWeek(date1, date3),
});
Output:

{
  "date1": "2023-02-05T00:00:00.000Z",
  "date2": "2023-02-06T00:00:00.000Z",
  "date3": "2023-02-12T00:00:00.000Z",
  "getWeekNum(date1)": 6,
  "getWeekNum(date2)": 6,
  "getWeekNum(date3)": 7,
  "isSameWeek(date1, date2)": true,
  "isSameWeek(date1, date3)": false
}

Notes:

  • always provide a proper ISO 8601 format format for the new Date() constructor
    • use format YYY-MM-DDTHH:mm:ss.sssZ for UTC date
    • use format YYY-MM-DDTHH:mm:ss.sss for local browser date
  • If you have a date string variable of format YYY-MM-DD you need to append THH:mm:ss.sssZ or THH:mm:ss.sss to get the full ISO 8601 format

Upvotes: 1

Related Questions