from Date I just want to subtract 1 day in javascript/angularjs
Solution 1
You need to specify what amount of time you are subtracting. At the moment its 1, but 1 what? Therefore, try getting the days using getDate()
and then subtract from that and then set the date with setDate()
.
E.g.
var temp = new Date("October 13, 2014 22:34:17");
temp.setDate(temp.getDate()-1);
Solution 2
The simple answer is that you want to subtract a days worth of milliseconds from it. So something like the following
var today = new Date('October 13, 2014 22:34:17');
var yesterday = new Date(today.getTime() - (24*60*60*1000));
console.log(yesterday);
The problem with this is that this really gives you 24 hours earlier, which isn't always a day earlier due to things such as changes in Daylight Saving Time. If this is what you want, fine. If you want something more sophisticated, check out moment.js
Solution 3
You can simply subtract one day from today date like this:
var yesterday = new Date(new Date().setDate(new Date().getDate()-1));
Related videos on Youtube
Codiee
Currently working on Angularjs, Angular2, Node, and AEM
Updated on February 16, 2020Comments
-
Codiee over 4 years
with the help of new Date() how i can achieve this. my code :
var temp =new Date("October 13, 2014 22:34:17"); console.log(new Date(temp-1));
requirement:
before: Aug 4, 2014 11:59pm (EDT) after: Aug 3, 2014 11:59pm (EDT)
-
Sani Singh Huttunen almost 10 yearspossible duplicate of Subtract days from a date in JavaScript
-
-
markhorrocks over 9 yearsJust do yesterday.sethours(23,59,59,999) to get yesterday's date at midnight.
-
yktoo over 8 yearsMilliseconds (1/1000), not microseconds (1/1000000).
-
seawave_23 over 4 yearsThis causes problems in case of summer/ winter time subtractions!
-
seawave_23 over 4 yearsthis even works with 0 and negatives, perfect, thanks!
-
Prisoner over 4 yearsAs noted in the answer: "this really gives you 24 hours earlier, which isn't always a day earlier due to things such as changes in Daylight Saving Time [the US name for Summer Time]". It is, however, appropriate for some uses where just subtracting the day is not.
-
Twitch over 3 yearsThis answer works best as it continues to support methods like
.getFullYear()
without any additional conversions. -
Salik almost 3 yearsThis doesn't work well if the new date is the first day of a month.
-
Salik almost 3 yearsWorks for me too. The first answer has a flaw when the new date is 1st of a month and you subtract1-2 days from it. Thanks.