如何根据当前日期显示两周期间的第一天

How can I display the first day of a two week period based on the current date with?

本文关键字:周期 第一天 两周 显示 何根 当前日期      更新时间:2023-09-26

我需要做的是获取当前日期,并根据今天的日期确定两周支付期的第一天。支付期从星期六开始。例如,今天(12/30)属于12/20的支付期。我需要做的就是将其显示为Dec 20 2014。有什么建议吗?

谢谢

使用此处的想法来计算两个日期之间的差异,您可以执行以下操作:

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对象。要设置显示日期的格式,您可以使用此答案。