What's the simplest way to decrement a date in Javascript by 1 day?

陌路散爱 提交于 2019-12-29 06:38:08

问题


I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.

It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way.

What's the simplest way of doing this?

[Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.]


回答1:


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

console.log(d);



回答2:


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



回答3:


 day.setDate(day.getDate() -1); //will be wrong

this will return wrong day. under UTC -03:00, check for

var d = new Date(2014,9,19);
d.setDate(d.getDate()-1);// will return Oct 17

Better use:

var n = day.getTime();
n -= 86400000;
day = new Date(n); //works fine for everything



回答4:


getDate()-1 should do the trick

Quick example:

var day = new Date( "January 1 2008" );
day.setDate(day.getDate() -1);
alert(day);



回答5:


origDate = new Date();
decrementedDate = new Date(origDate.getTime() - (86400 * 1000));

console.log(decrementedDate);



回答6:


setDate(dayValue)

dayValue is an integer from 1 to 31, representing the day of the month.

from https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setDate

The behaviour solving your problem (and mine) seems to be out of specification range.

What seems to be needed are addDate(), addMonth(), addYear() ... functions.




回答7:


Working with dates in JS can be a headache. So the simplest way is to use moment.js for any date operations.

To subtract one day:

const date = moment().subtract(1, 'day')


来源:https://stackoverflow.com/questions/31931/whats-the-simplest-way-to-decrement-a-date-in-javascript-by-1-day

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