Subtract days from a date in JavaScript

2018-12-31 09:00发布

Does anybody know of an easy way of taking a date (e.g. Today) and going back X days?

So, for example, if I want to calculate the date 5 days before today.

30条回答
深知你不懂我心
2楼-- · 2018-12-31 09:33

without using the second variable, you can replace 7 for with your back x days

let d=new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000))

查看更多
人气声优
3楼-- · 2018-12-31 09:33

var d = new Date();

document.write('Today is: ' + d.toLocaleString());

d.setDate(d.getDate() - 100);

document.write('<br>100 days ago was: ' + d.toLocaleString());

查看更多
旧时光的记忆
4楼-- · 2018-12-31 09:34

function addDays (date, daysToAdd) {
  var _24HoursInMilliseconds = 86400000;
  return new Date(date.getTime() + daysToAdd * _24HoursInMilliseconds);
};

var now = new Date();

var yesterday = addDays(now, - 1);

var tomorrow = addDays(now, 1);

查看更多
栀子花@的思念
5楼-- · 2018-12-31 09:34

You can using 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

For PHP,

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

Hope it will help you.

查看更多
无色无味的生活
6楼-- · 2018-12-31 09:35

split your date into parts, then return a new Date with the adjusted values

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);
}

Remember that the months are zero based, but the days are not. ie new Date(2009, 1, 1) == 01 February 2009, new Date(2009, 1, 0) == 31 January 2009;

查看更多
还给你的自由
7楼-- · 2018-12-31 09:36
var daysToSubtract = 3;
$.datepicker.formatDate('yy/mm/dd', new Date() - daysToSubtract) ;
查看更多
登录 后发表回答