Using the ideas here for working out the difference between two dates, you can do the following:
function calculatePeriodStart(targetDate) {
// get first day of year
var day1 = new Date(targetDate.getFullYear(), 0, 1);
// move forward to first Saturday
day1.setDate(7 - day1.getDay());
//Get 2 weeks in milliseconds
var two_weeks = 1000 * 60 * 60 * 24 * 14;
// Calculate the difference in milliseconds
var difference_ms = targetDate.getTime() - day1.getTime();
// Convert back to fortnights
var numFortnightsD = difference_ms/two_weeks;
var numFortnights = Math.ceil(numFortnightsD);
// handle if on a Saturday, so a new cycle
if(numFortnightsD == numFortnights)
{
numFortnights++;
}
// add the number of fortnights
// but take one off to get the current period
day1.setDate(day1.getDate() + (numFortnights-1)*14);
return day1;
}
// examples
console.log('-----');
// today
var today = new Date();
console.log(today + ' => ' + calculatePeriodStart(today) + ' (today)');
// just before midnight of new period
var today = new Date(2014, 11, 19, 23, 59, 59);
console.log(today + ' => ' + calculatePeriodStart(today) + ' (just before midnight of new period)');
// exactly on midnight of new period
today = new Date(2014, 11, 20);
console.log(today + ' => ' + calculatePeriodStart(today) + ' (exactly on midnight of new period)');
// just after midnight of new period
today = new Date(2014, 11, 20, 0, 0, 1)
console.log(today + ' => ' + calculatePeriodStart(today) + ' (just after midnight of new period)');
// just after midnight of new period next year
today = new Date(2015, 11, 19, 0, 0, 1);
console.log(today + ' => ' + calculatePeriodStart(today) + ' (just after midnight of new period next year)');
// earlier than 1st period in year
today = new Date(2014, 0, 2);
console.log(today + ' => ' + calculatePeriodStart(today) + ' (earlier than 1st period in year)');
calculatePeriodStart()
will return a Date
object. To format the date for display, you can use this answer.