有没有一种简单的方法来获取olain JavaScript日期(例如今天)并返回X天?

例如,如果我想计算今天前5天的日期。


当前回答

我注意到getDays+X在日/月范围内不起作用。只要您的日期不早于1970年,就可以使用getTime。

var todayDate = new Date(), weekDate = new Date();
weekDate.setTime(todayDate.getTime()-(7*24*3600000));

其他回答

将日期拆分为多个部分,然后返回一个具有调整值的新日期

function DateAdd(date, type, amount){
    var y = date.getFullYear(),
        m = date.getMonth(),
        d = date.getDate();
    if(type === 'y'){
        y += amount;
    };
    if(type === 'm'){
        m += amount;
    };
    if(type === 'd'){
        d += amount;
    };
    return new Date(y, m, d);
}

记住,月份是以零为基础的,但日子不是。即新日期(2009,1,1)==2009年2月1日,新日期(2009,1,0)==2009年1月31日;

使用MomentJS。

函数getXDaysBeforeDate(referenceDate,x){return moment(referenceDate).减去(x,'day').格式('MMMM Do YYYY,h:mm:ss a');}var yourDate=新日期();//就说今天吧var valueOfX=7;//假设7天前console.log(getXDaysBeforeDate(yourDate,valueOfX));<script src=“https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js“></script>

我换算成毫秒,扣除天数,否则一个月和一年都不会改变,符合逻辑

var numberOfDays = 10;//number of days need to deducted or added
var date = "01-01-2018"// date need to change
var dt = new Date(parseInt(date.substring(6), 10),        // Year
              parseInt(date.substring(3,5), 10) - 1, // Month (0-11)
              parseInt(date.substring(0,2), 10));
var new_dt = dt.setMilliseconds(dt.getMilliseconds() - numberOfDays*24*60*60*1000);
new_dt = new Date(new_dt);
var changed_date = new_dt.getDate()+"-"+(new_dt.getMonth()+1)+"-"+new_dt.getFullYear();

希望有帮助

您可以使用Javascript。

var CurrDate = new Date(); // Current Date
var numberOfDays = 5;
var days = CurrDate.setDate(CurrDate.getDate() + numberOfDays);
alert(days); // It will print 5 days before today

对于PHP,

$date =  date('Y-m-d', strtotime("-5 days")); // it shows 5 days before today.
echo $date;

希望它对你有所帮助。

设置日期时,日期转换为毫秒,因此需要将其转换回日期:

这种方法还考虑了新年变化等因素。

function addDays( date, days ) {
    var dateInMs = date.setDate(date.getDate() - days);
    return new Date(dateInMs);
}

var date_from = new Date();
var date_to = addDays( new Date(), parseInt(days) );