在javascript中使用当前日期获取两周日期

Get fortnight date using current date in javascript

本文关键字:获取 两周 日期 当前日期 javascript      更新时间:2023-09-26

我正试图在javascript中编写代码,以获得两周(2周)日期从今天的日期。有什么建议或帮助吗?

首先得到当前日期,然后加上14天(2周),最后得到该周的最后一天:

// Get todays day
var now = new Date();
// Add 2 weeks
now.setTime( now.getTime() + 14 * 86400000 );
// Then go to the last day of that week
var fortnight = new Date(now.setDate(now.getDate() - now.getDay()+6));
console.log(fortnight);

使用以下函数,您可以获得任何日期的两周日期。

function getFortNightDate(sDate){
    var param = [];
    var objDate = new Date();
    param.todayDate = objDate.getFullYear() + '-' + ("0" + (objDate.getMonth() + 1)).slice(-2) + '-' + ("0" + (objDate.getDate())).slice(-2);
    param.timeDiff = Math.abs(new Date(param.todayDate).getTime() - new Date(sDate).getTime());
    param.diffDays = Math.ceil(param.timeDiff / (1000 * 3600 * 24));
    param.dayCount = (14 - (param.diffDays % 14)) - 1;
    objDate.setDate(objDate.getDate() + param.dayCount);
    objDate = objDate.getFullYear() + '-' + ("0" + (objDate.getMonth() + 1)).slice(-2) + '-' + ("0" + (objDate.getDate())).slice(-2);
    return objDate;
}