0

I am trying to find the number of weeks or number of months between two dates. I have written the following but it does not work for the case when we have 53 weeks. I am unable to find a proper way to do this.

getNumOfWeeksOrMonths(fromDate:Moment, toDate:Moment, frequency:string){
      let numberWeeksMonths;
      if(frequency === 'months'){
           console.log("Returning months");
            numberWeeksMonths =moment(toDate).diff(moment(fromDate), 'months');
        }
     else{
         console.log("Returning weeks");
         numberWeeksMonths =moment(toDate).diff(moment(fromDate), 'weeks');
     }
    return numberWeeksMonths; 
}

UPDATE: I am able to get the weeks as follows

      let startDate = fromDate.toDate();
      let endDate =  toDate.toDate();
      var week = 1000 * 60 * 60 * 24 * 7;
      let weeksBetween = Math.ceil((endDate.getTime() - startDate.getTime())/ONE_WEEK)

This gives me correctly 52 weeks in 2019 and 53 weeks in 2020. However when I do a date range say 10/19/2020 to 11/30/2020 I get 7 weeks instead of 6. Any idea on how to fix this?

Mary
  • 1,505
  • 5
  • 27
  • 44
  • Do you mean startDate instead of fromDate and endDate instead of toDate here: numberWeeksMonths =moment(toDate).diff(moment(fromDate), 'weeks');? – greatromul Oct 22 '20 at 15:05
  • Please check this below links https://stackoverflow.com/questions/22859704/number-of-weeks-between-two-dates-using-javascript – Sumanth Itha Oct 22 '20 at 15:06
  • I tried with moment, using the diff function.However for a fromDate 01/01/2020 and endDate 12/31/2020 it is returning 52 weeks instead of 53 – Mary Oct 22 '20 at 17:00
  • @SumanthItha - I am tying with the link you showed but it is not returning the right answer.For instance number of weeks between 12/31/2020 and 01/01/2020 is returning 5 weeks – Mary Oct 22 '20 at 17:44
  • Why would 01/01/2020 and 12/31/2020 return something other than 52 weeks? After all, there are 52 weeks in a year? - also, make sure you are passing in dates in the correct format for the moment library, it sounds like you might be flipping DD and MM – katamaster818 Oct 22 '20 at 22:36

1 Answers1

0

I was able to solve this by using Math.floor and identifying those weeks that were greater than 52, those were set to 53

Mary
  • 1,505
  • 5
  • 27
  • 44