from Date I just want to subtract 1 day in javascript/angularjs

57,828

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));
Share:
57,828

Related videos on Youtube

Codiee
Author by

Codiee

Currently working on Angularjs, Angular2, Node, and AEM

Updated on February 16, 2020

Comments

  • Codiee
    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)
    
  • markhorrocks
    markhorrocks over 9 years
    Just do yesterday.sethours(23,59,59,999) to get yesterday's date at midnight.
  • yktoo
    yktoo over 8 years
    Milliseconds (1/1000), not microseconds (1/1000000).
  • seawave_23
    seawave_23 over 4 years
    This causes problems in case of summer/ winter time subtractions!
  • seawave_23
    seawave_23 over 4 years
    this even works with 0 and negatives, perfect, thanks!
  • Prisoner
    Prisoner over 4 years
    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.
  • Twitch
    Twitch over 3 years
    This answer works best as it continues to support methods like .getFullYear() without any additional conversions.
  • Salik
    Salik almost 3 years
    This doesn't work well if the new date is the first day of a month.
  • Salik
    Salik almost 3 years
    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.