Javascript日期落后

时间:2016-11-25 17:07:58

标签: javascript date

我试图在使用前计算一天的日期:

var da = new Date('2016-11-25');
nda = new Date(da-86400000);

使用以下打印出来似乎效果很好:

document.write(nda);

输出结果为:

2016年11月24日星期四00:00:00 GMT + 0000(WET)

这是正确的,但是当我这样做时:

document.write(nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay());

输出错误:

2016年10月4日

有什么建议吗?

4 个答案:

答案 0 :(得分:2)

您需要nda.getMonth() + 1。 月份从0开始,因此为了获得正确的月份数,您必须添加1。

此外,您需要使用getDate()代替getDay()。 getDay将为您提供一周中的某一天,而getDate将为您提供当月的日期。

最终结果将是:

nda.getFullYear() + "-" + (nda.getMonth() + 1) + "-" + nda.getDate()

答案 1 :(得分:0)



var da = new Date('2016-11-25');
nda = new Date(da-86400000);

document.write((nda.getFullYear())+
               "-"+(nda.getMonth()+1)+
               "-"+(nda.getDate()));




答案 2 :(得分:0)

Date.getMonth()返回月份索引,该索引为0索引(因此0表示1月,11表示12月)。要纠正此问题,请添加1。

Date.getDay()返回星期几,从星期日开始也是0索引(所以4星期四)。

在这里,您可以使用Date.getDate()来获取当月的日期(不是0索引)。



var da = new Date('2016-11-25'),
nda = new Date(da-86400000);
document.write(nda.getFullYear() + "-" +
               (nda.getMonth() + 1) + "-" +
                nda.getDate());




答案 3 :(得分:-2)

解析日期有一个基本规则:不要使用Date构造函数或Date.parse(它们等同于解析)来解析日期字符串。使用带解析器的库或使用简单的函数自行解析。

使用时:

var da = new Date('2016-11-25');

日期将被视为UTC,因此如果您位于格林威治以西的时区,则当地日期将是前一天。请注意以下差异:

console.log('Built-in parse: ' + new Date('2016-11-25').toLocaleString());
console.log('No parse      : ' + new Date(2016, 10, 25).toLocaleString());

当你这样做时:

nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay();

正如其他人所说,你应该使用nda.getMonth() + 1,而你想要 getDate 而不是 getDay 。但是,由于您将日期解析为UTC然后获取本地值,因此UTC的上一个问题可能意味着该日期是前一天。

要在本地时区构建日期并避免解析错误,请直接设置值。

要获得任何日期前一天,只需减去一天。不要减去24小时,否则你会在夏令时边界上得到错误(因为那些日子并不完全是24小时)。 e.g:

/* Format a date as yyyy-mm-dd
** @param {Date} date
** @returns {string}
*/
function formatDate(date) {
  return date.getFullYear() + '-' +
        ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
        ('0' + date.getDate()).slice(-2); 
}

var nda = new Date(2016, 10, 25);
console.log('Created date: ' + formatDate(nda));

nda.setDate(nda.getDate() - 1);
console.log('Previous day: ' + formatDate(nda));