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

前端 未结 3 1261
暖寄归人
暖寄归人 2021-02-04 09:05

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));

相关标签:
3条回答
  • 2021-02-04 09:49

    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);
    
    0 讨论(0)
  • 2021-02-04 09:52

    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

    0 讨论(0)
  • 2021-02-04 09:57

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

    var yesterday = new Date(new Date().setDate(new Date().getDate()-1));
    
    0 讨论(0)
提交回复
热议问题