Since you're using date-fns, the differenceInWeeks
method might be your best best. (There is also a differenceInCalendarWeeks
method, but I do not think you need the weekStartsOn
functionality that it offers.)
(A vanilla JavaScript solution could be built from this answer, if desired.)
From the date-fns documentation:
// How many full weeks are between 5 July 2014 and 20 July 2014?
var result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))
//=> 2
You could use this information to calculate the number of two-week periods from your initial endDate
:
var result = Math.ceil(differenceInWeeks(randomDate, endDate)/2)
// Returns number of pay period after endDate
For dates that are before or including endDate
, it would need to look like this:
var refDate = addDays(endDate, 1); // using refDate ensures full weeks for calculation
var result = Math.ceil(differenceInWeeks(refDate, randomDate)/2)
// Returns number of pay period before endDate (1 is endDate's pay period)
Then, to get the specific dates for the resulting pay periods, use the date-fns add() or sub() functions to get the end date of the pay period in question. (Unfortunately, these functions do not have a weeks
option, so you will need to convert the number of weeks to days) Example for a randomDate
after endDate
:
var result = Math.ceil(differenceInWeeks(randomDate, endDate)/2)
var newEndDate = add(endDate, {days: result*14}); // *2 for weeks, *7 for days
// Returns end date of pay period containing randomDate after endDate
Example for randomDate before or including endDate (note this returns the start date):
var refDate = addDays(endDate, 1); // using refDate ensures full weeks for calculation
var result = Math.ceil(differenceInWeeks(refDate, randomDate)/2)
var newStartDate = sub(refDate, {days: result*14}); // *2 for weeks, *7 for days
// Returns start date of pay period containing randomDate before endDate, inclusive
You did not provide a desired output format, but you should then be able to manipulate these results for your calendar to highlight the correct dates.