我需要做的是取当前日期,并根据今天的日期确定两周付款期的第一天。支付期从星期六开始。例如,今天(12/30)属于12/20的支付期。我需要处理的所有信息都显示为2014年12月20日。有任何建议吗?
由于
答案 0 :(得分:0)
使用构思here来计算两个日期之间的差异,您可以执行以下操作:
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()
将返回Date
个对象。要格式化显示日期,您可以使用this answer。