如何获得“日期前一天”在JavaScript中? [英] How to get "the day before a date" in javascript?
问题描述
这两个堆栈溢出问题提出了类似的问题,但他们的解决方案对我来说似乎不起作用:
昨天的Javascript
Javascript代码显示昨天的日期和今天的日期
These two stack overflow questions ask a similar question, but their solution doesn't seem to work for me: Javascript Yesterday Javascript code for showing yesterday's date and todays date
鉴于日期,我需要前一天的日期(前一天)。以上是上面提出的解决方案,以及一个对我不起作用的场景:
http:// jsfiddle.net/s3dHV/
Given a date, I need the date of the prior day (the day before). Here's a fiddle with the solution suggested above, and a scenario that doesn't work for me: http://jsfiddle.net/s3dHV/
var date = new Date('04/28/2013 00:00:00');
var yesterday = new Date();
yesterday.setDate(date.getDate() - 1);
alert('If today is ' + date + ' then yesterday is ' + yesterday);
对我来说,警报
如果今天是2013年4月28日星期日00:00:00 GMT-0400(东部夏令时)
然后昨天是2013年5月27日星期一11:12:06 GMT-0400(东部
日光时间)。
If today is Sun Apr 28 2013 00:00:00 GMT-0400 (Eastern Daylight Time) then yesterday is Monday May 27 2013 11:12:06 GMT-0400 (Eastern Daylight Time).
这显然是不正确的。为什么?
Which is obviously incorrect. Why?
推荐答案
你正在制作一个全新的日期。
You're making a whole new date.
var yesterday = new Date(date.getTime());
yesterday.setDate(date.getDate() - 1);
这将使你成为第一次约会的副本。当你调用 setDate()
时,它只会影响月日,而不是整个事情。如果您从原始日期的副本开始,然后设置月份的日期,您将得到正确的答案。
That'll make you a copy of the first date. When you call setDate()
, it just affects the day-of-the-month, not the whole thing. If you start with a copy of the original date, and then set the day of the month back, you'll get the right answer.
这篇关于如何获得“日期前一天”在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!