0

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.

James Z
  • 12,209
  • 10
  • 24
  • 44
  • 1
    [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – Andreas Sep 25 '21 at 11:27
  • Can you show the code that you have written in your attempt? – RWRkeSBZ Sep 25 '21 at 11:27
  • Hi ! You formulation sounds very "directive" :D Have you made a simple copy/past of what you are asked to achieve ? ;) – Philippe Sep 25 '21 at 11:32
  • I don't have any sample code, I just stuck in how I can check the two dates are in same week or not. – Gunjan Kiratkar Sep 25 '21 at 11:32
  • Find a way to get the week a date is in. Compare. -> [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Sep 25 '21 at 11:34
  • Hi @Philippe, I'm doing this for knowledge gaining in Javascript. I literally search about this on google but didn't get anything. – Gunjan Kiratkar Sep 25 '21 at 11:34
  • Ok ok. What about the logic to determine if two dates are in the same week ? In fact I never looked for a solution to this question, but indeed it is very interesting ! I think I'm going to work on it by my side, regardless of the language I'm going to use at the end of the process :) – Philippe Sep 25 '21 at 11:42

1 Answers1

1

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')
Carlos Menezes
  • 314
  • 1
  • 8
  • Code–only answers aren't helpful. Neither this or the OP define "week" or "same week", nor how they work, nor any limitations or caveats. If the answer is given in another answer on SO, then this is a duplicate and should be closed as such. Various other posts such as [*Get week of year in JavaScript like in PHP*](https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php) with 24 answers explain different algorithms and concepts of "week". – RobG Sep 26 '21 at 01:01