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:37

Using Modern JavaScript function syntax

const getDaysPastDate = (daysBefore, date = new Date) => new Date(date - (1000 * 60 * 60 * 24 * daysBefore));

console.log(getDaysPastDate(1)); // yesterday

查看更多
初与友歌
3楼-- · 2018-12-31 09:37
var my date = new Date().toISOString().substring(0, 10);

it can give you only date like 2014-06-20. hope will help

查看更多
何处买醉
4楼-- · 2018-12-31 09:39

I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.

function dateManipulation(date, days, hrs, mins, operator) {
   date = new Date(date);
   if (operator == "-") {
      var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
      var newDate = new Date(date.getTime() - durationInMs);
   } else {
      var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
      var newDate = new Date(date.getTime() + durationInMs);
   }
   return newDate;
 }

Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.

var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");
查看更多
荒废的爱情
5楼-- · 2018-12-31 09:41

I made this prototype for Date so that I could pass negative values to subtract days and positive values to add days.

if(!Date.prototype.adjustDate){
    Date.prototype.adjustDate = function(days){
        var date;

        days = days || 0;

        if(days === 0){
            date = new Date( this.getTime() );
        } else if(days > 0) {
            date = new Date( this.getTime() );

            date.setDate(date.getDate() + days);
        } else {
            date = new Date(
                this.getFullYear(),
                this.getMonth(),
                this.getDate() - Math.abs(days),
                this.getHours(),
                this.getMinutes(),
                this.getSeconds(),
                this.getMilliseconds()
            );
        }

        this.setTime(date.getTime());

        return this;
    };
}

So, to use it i can simply write:

var date_subtract = new Date().adjustDate(-4),
    date_add = new Date().adjustDate(4);
查看更多
何处买醉
6楼-- · 2018-12-31 09:41

I get good mileage out of date.js:

http://www.datejs.com/

d = new Date();
d.add(-10).days();  // subtract 10 days

Nice!

Website includes this beauty:

Datejs doesn’t just parse strings, it slices them cleanly in two

查看更多
刘海飞了
7楼-- · 2018-12-31 09:42

I noticed that the getDays+ X doesn't work over day/month boundaries. Using getTime works as long as your date is not before 1970.

var todayDate = new Date(), weekDate = new Date();
weekDate.setTime(todayDate.getTime()-(7*24*3600000));
查看更多
登录 后发表回答