How to subtract days from a plain Date?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Is there an easy way of taking a olain JavaScript Date (e.g. today) and going back X days? So, for example, if I want to calculate the date 5 days before today.
37 Answers 37
var d = new Date(); d.setDate(d.getDate() - 5);
Note that this modifies the date object and returns the time value of the updated date.
var d = new Date(); document.write('Today is: ' + d.toLocaleString()); d.setDate(d.getDate() - 5); document.write('
5 days ago was: ' + d.toLocaleString());
Given that this is at the top of google, I figure I’d answer the above comment: new Date(new Date().setDate(new Date().getDate()-5)) — that will be 5 days ago. In the example of the answer, pass it to a new date to get a date object. So new Date(d) is what you want.
@user525146 asked how to format the number, not what the number is. There’s no need for condescending answers. To format the number, use one of the Date toString methods like toISOString , toDateString , etc.
var dateOffset = (24*60*60*1000) * 5; //5 days var myDate = new Date(); myDate.setTime(myDate.getTime() - dateOffset);
If you’re performing lots of headachy date manipulation throughout your web application, DateJS will make your life much easier:
it’s an edge case, but this can fail around the start/end of daylight saving time. you’re not subtracting 5 days, but 5*24 hours. the first day of daylight saving time is only 23 hours long, and the last is 25 hours long. it usually doesn’t matter, but it’s something to consider.
@cwallenpoole not to burst your bubble, but they use DST even in Greenwich. So if you really want to be on GMT, you’re restricted to Iceland and a few west-African countries.
@danielWilliams How does this not work with a new year? getTime() and setTime() are milliseconds since the epoch. It shouldn’t matter if the time crosses a year boundary.
It goes something like this:
var d = new Date(); // today! var x = 5; // go back 5 days! d.setDate(d.getDate() - x);
The return value of d.setDate is indeed an integer value. However, you are probably not actually interested in the return value at this point, since the actual value of «d» has been modified. Your real question is now how to format your date, which is now in «d» and not the return value of setDate at all. (Well, it actually is the return value, but it is not a date by that point and I do not wish to confuse you—just use d, it will be quicker). For formatting dates, you want the d.getMonth(), d.getFullYear(), and d.getDate() methods. You want to add one to d.getMonth(), since Jan is 0.
If you want it all on one line instead.
//past var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5)); //future var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5));
5 days from a specific date
var pastDate = new Date('2019-12-12T00:00:00'); //past var fiveDaysAgo = new Date(new Date().setDate(pastDate.getDate() - 5)); //future var fiveDaysInTheFuture = new Date(new Date().setDate(pastDate.getDate() + 5));
I wrote a function you can use.
function AddOrSubractDays(startingDate, number, add) < if (add) < return new Date(new Date().setDate(startingDate.getDate() + number)); >else < return new Date(new Date().setDate(startingDate.getDate() - number)); >> console.log('Today : ' + new Date()); console.log('Future : ' + AddOrSubractDays(new Date(), 5, true)); console.log('Past : ' + AddOrSubractDays(new Date(), 5, false));
Welcome to Stack Overflow _ Although you have given a good coded answer the comment post at the top (yellow background) specifically states that «that provide some explanation and context» are required & «explain why your answer is right, ideally with citations» _ Please edit your answer with the above requirements
@MartinKomischke you are right. I must have missed that during my copy paste from where I was actually using it for work. Good catch!
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));
This is also incorrect around the edge case of start/end of daylight saving time. Your approach is subtracting 7*24 hours, under the assumption that every day has 24 hours. The first day of DST is only 23 hours long, and the last day is 25 hours long. setDate(getDate()-7) does not have this problem.
getTime works off universal time. So will correctly subtract 7 days time from the Date object. When you convert it to a string in your specified time zone it will correctly show the time for that zone.
Be careful on the time change day. When we fall back in fall, that day has 25 hours, so subtracting 24 hours from midnight will land you in the same day. But this technique (subtracting milliseconds) WILL work if you round off the day after every operation to the nearest midnight. You can do that by first adding 12 hours, then setting the hours to zero.
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))
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.
This may give an incorrect result if the code is run near 2am and daylight savings time has changed within the last 5 days.
get moment.js. All the cool kids use it. It has more formatting options, etc. Where
var n = 5; var dateMnsFive = moment().subtract(n , 'day');
Optional! Convert to JS Date obj for Angular binding.
var date = new Date(dateMnsFive.toISOString());
var date = dateMnsFive.format("YYYY-MM-DD");
by passing your date into moment, you will start getting warnings. Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to momentjs.com/guides/#/warnings/js-date for more info.
A few of the existing solutions were close, but not quite exactly what I wanted. This function works with both positive or negative values and handles boundary cases.
function addDays(date, days)
does it ‘spill’ over to next month if I use this method to add 20 days to 15th of current month? It does not seem to.
@Bora — yes, it correctly increments the month if necessary. For example, adding 20 days to Aug 15: addDays(new Date(2015, 07, 15), 20) will return «Fri Sep 04 2015 00:00:00 GMT-0700 (PDT)»
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))
I commented this on another entry, but it holds true here too: due to time adjustments not all days are 86.4m milliseconds. This could distort the result by +/- 1 day
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);
You can use d.setDate(d.getDate() + days) with both positive and negative values for days to add and subtract days respectively. And it should work on the instance (as other Date methods do), not create and return a copy.
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;
What happens if you add for example 50 days to a date this way? Will it set the date to 68 August 2009? Or are you sure that this always wraps over to the appropriate month and/or year correctly?
This should be the correct answer — it works even on the last day of the year when the accepted answer fails.
Doesn’t work for dates with years from 1 to 99. 😉 Much better to just use the get* and set* methods.
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
Subtract days, months, years from a date in JavaScript
Does anybody know of a simple way of taking a date (e.g. Today) and going back X days, X months and X years? I have tried that:
var date = new Date(); $("#searchDateFrom").val((date.getMonth() -1 ) + '/' + (date.getDate() - 6) + '/' + (date.getFullYear() - 1));
date.get. will return a Number and if you are subtracting number from another number , value can be negative(If left value is smaller).. I would suggest you to use DateObj.set. methods and then retrieve the respective values.
10 Answers 10
You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.
You need to individually add/remove unit of time in date object
var date = new Date(); date.setDate( date.getDate() - 6 ); date.setFullYear( date.getFullYear() - 1 ); $("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));
But getMinutes() for example isn’t index-based. So it’s fair to say the inconsistency is wrong as @Tony puts it.
As others have said you’re subtracting from the numeric values returned from methods like date.getDate() , you need to reset those values on your date variable. I’ve created a method below that will do this for you. It creates a date using new Date() which will initialize with the current date, then sets the date, month, and year according to the values passed in. For example, if you want to go back 6 days then pass in -6 like so var newdate = createDate(-6,0,0) . If you don’t want to set a value pass in a zero (or you could set default values). The method will return the new date for you (tested in Chrome and Firefox).
function createDate(days, months, years)
JavaScript Date minus 1 day
You can use the getTime() method or the setDate() method to Date minus 1 day in JavaScript. Both approaches allow you to work with dates and times in JavaScript.
JavaScript Date minus 1-day example
A simple example code modifies the Date object and obtains the previous day’s date and time.
Alternatively, you can use the setDate() method to modify the Date object in place:
const today = new Date(); today.setDate(today.getDate() - 1);
How to subtract days from a plain Date?
Answer: To subtract days from a plain Date object in JavaScript, you can use the setDate() and getDate() methods to modify the day of the month. Here’s an example:
const date = new Date('2023-03-28'); // create a new date object for March 28, 2023 const daysToSubtract = 7; // subtract 7 days date.setDate(date.getDate() - daysToSubtract); // modify the date object to subtract 7 days console.log(date); // output: Tue Mar 21 2023 00:00:00 GMT-0700 (Pacific Daylight Time)
Do comment if you have any doubts or suggestions on this Js date topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version