Home > Back-end >  Check if two dates are present in same week or not. (In JS)
Check if two dates are present in same week or not. (In JS)

Time:09-25

E.g. Input 1:----- date 1='2021-09-20' date 2='2021-09-24'

Output 1:---- Present in same week

Input 2:------ date 1='2021-09-24' date 2='2021-09-27'

Output 1:---- Not in same week

Please provide solution in javascript.

CodePudding user response:

const getWeek = (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 getWeek(dateA) === getWeek(dateB);
}

const dateA = new Date('2021-09-20')
const dateB = new Date('2021-09-24')
const dateC = new Date('2021-09-27')
console.log(isSameWeek(dateA, dateB));
console.log(isSameWeek(dateA, dateC));

A momentjs one-liner:

moment().format('W')
  • Related