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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 09:20:59

问题


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)

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



回答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




回答3:


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

var yesterday = new Date(new Date().setDate(new Date().getDate()-1));


来源:https://stackoverflow.com/questions/25136760/from-date-i-just-want-to-subtract-1-day-in-javascript-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!