javascript 如何在javascript中获得“约会前一天”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16401804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:30:58  来源:igfitidea点击:

How to get "the day before a date" in javascript?

javascript

提问by Arbiter

These two stack overflow questions ask a similar question, but their solution doesn't seem to work for me: Javascript YesterdayJavascript code for showing yesterday's date and todays date

这两个堆栈溢出问题提出了一个类似的问题,但他们的解决方案似乎对我不起作用: Javascript Yesterday Javascript code for shows today's date and todays date

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/

给定一个日期,我需要前一天(前一天)的日期。这是上面建议的解决方案的小提琴,以及对我不起作用的场景: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);

For me, that alerts

对我来说,这提醒

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

如果今天是 2013 年 4 月 28 日星期日 00:00:00 GMT-0400(东部夏令时间),那么昨天是 2013 年 5 月 27 日星期一 11:12:06 GMT-0400(东部夏令时间)。

Which is obviously incorrect. Why?

这显然是不正确的。为什么?

回答by Pointy

You're making a whole new date.

你在进行一个全新的约会。

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

That'll make you a copyof 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.

那会让你复制第一次约会。当您调用 时setDate(),它只会影响月份中的某一天,而不是整个事情。如果您从原始日期的副本开始,然后将月份中的日期重新设置,您将得到正确的答案。

回答by Vadim

Try this:

试试这个:

var date = new Date('04/28/2013 00:00:00');
var yesterday = new Date(date.getTime() - 24*60*60*1000);

回答by Riyanto Wibowo

var allmonths = [
    '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'
];
var alldates = [
    '01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
    '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
    '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'
];

var today = "2014-12-25";   
var aDayBefore = new Date(today);
aDayBefore.setDate(aDayBefore.getDate() - 1);

document.write(aDayBefore.getFullYear() 
  + '-' + allmonths[aDayBefore.getMonth()] 
  + '-' + alldates[aDayBefore.getDate() - 1]);