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

I find a problem with the getDate()/setDate() method is that it too easily turns everything into milliseconds, and the syntax is sometimes hard for me to follow.

Instead I like to work off the fact that 1 day = 86,400,000 milliseconds.

So, for your particular question:

today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))

Works like a charm.

I use this method all the time for doing rolling 30/60/365 day calculations.

You can easily extrapolate this to create units of time for months, years, etc.

查看更多
忆尘夕之涩
3楼-- · 2018-12-31 09:54

for me all the combinations worked fine with below code snipplet , the snippet is for Angular-2 implementation , if you need to add days , pass positive numberofDays , if you need to substract pass negative numberofDays

function addSubstractDays(date: Date, numberofDays: number): Date {
let d = new Date(date);
return new Date(
    d.getFullYear(),
    d.getMonth(),
    (d.getDate() + numberofDays)
);
}
查看更多
妖精总统
4楼-- · 2018-12-31 09:56

It goes something like this:

var d = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);
查看更多
宁负流年不负卿
5楼-- · 2018-12-31 09:57

get moment.js. All the cool kids use it. It has more formatting options, etc. Where

var n = 5;
var dateMnsFive = moment(<your date>).subtract(n , 'day');

Optional! Convert to JS Date obj for Angular binding.

var date = new Date(dateMnsFive.toISOString());

Optional! Format

var date = dateMnsFive.format("YYYY-MM-DD");
查看更多
一个人的天荒地老
6楼-- · 2018-12-31 10:00

I like doing the maths in milliseconds. So use Date.now()

var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds

and if you like it formatted

new Date(newDate).toString(); // or .toUTCString or .toISOString ...

NOTE: Date.now() doesn't work in older browsers (eg IE8 I think). Polyfill here.

UPDATE June 2015

@socketpair pointed out my sloppiness. As s/he says "Some day in year have 23 hours, and some 25 due to timezone rules".

To expand on that, the answer above will have daylightsaving inaccuracies in the case where you want to calculate the LOCAL day 5 days ago in a timezone with daylightsaving changes and you

  • assume (wrongly) that Date.now() gives you the current LOCAL now time, or
  • use .toString() which returns the local date and therefore is incompatible with the Date.now() base date in UTC.

However, it works if you're doing your math all in UTC, eg

A. You want the UTC date 5 days ago from NOW (UTC)

var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds UTC
new Date(newDate).toUTCString(); // or .toISOString(), BUT NOT toString

B. You start with a UTC base date other than "now", using Date.UTC()

newDate = new Date(Date.UTC(2015, 3, 1)).getTime() + -5*24*3600000;
new Date(newDate).toUTCString(); // or .toISOString BUT NOT toString
查看更多
人气声优
7楼-- · 2018-12-31 10:00
var today = new Date();
var tmpDate = new Date();
var i = -3; var dateArray = [];
while( i < 4 ){
    tmpDate = tmpDate.setDate(today.getDate() + i);
  tmpDate = new Date( tmpDate );
  var dateString = ( '0' + ( tmpDate.getMonth() + 1 ) ).slice(-2) + '-' + ( '0' + tmpDate.getDate()).slice(-2) + '-' + tmpDate.getFullYear();
    dateArray.push( dateString );
    i++;
}
console.log( dateArray );
查看更多
登录 后发表回答