15

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)
Robert
  • 1,286
  • 1
  • 17
  • 37
Codiee
  • 3,047
  • 2
  • 17
  • 18
  • 6
    possible duplicate of [Subtract days from a date in JavaScript](http://stackoverflow.com/questions/1296358/subtract-days-from-a-date-in-javascript) – Sani Huttunen Aug 05 '14 at 10:40

4 Answers4

42

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);
AndrewPolland
  • 3,041
  • 4
  • 28
  • 39
13

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

Kayvan Mazaheri
  • 2,447
  • 25
  • 40
Prisoner
  • 49,922
  • 7
  • 53
  • 105
  • Just do yesterday.sethours(23,59,59,999) to get yesterday's date at midnight. – markhorrocks Oct 22 '14 at 06:20
  • 1
    Milliseconds (1/1000), not microseconds (1/1000000). – yktoo Mar 14 '16 at 16:02
  • This causes problems in case of summer/ winter time subtractions! – seawave_23 Nov 21 '19 at 12:15
  • 1
    As 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. – Prisoner Nov 21 '19 at 13:04
7

You can simply subtract one day from today date like this:

var yesterday = new Date(new Date().setDate(new Date().getDate()-1));
SKL
  • 1,243
  • 4
  • 32
  • 53
  • This answer works best as it continues to support methods like `.getFullYear()` without any additional conversions. – Twitch Feb 17 '21 at 20:33
  • Works 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. – Salik Sep 01 '21 at 13:25
0

Simply subtract from one date to the next Date. You can do so by clicking on this link for subtracting the date. following this url.

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/33810903) – Moritz Ringler Feb 13 '23 at 14:52