如何在JavaScript中计算昨天作为日期?
当前回答
解决边界日期问题(2020,01,01)-> 2019,12,31
var now = new Date();
return new Date(now.getMonth() - 1 === 0 ? now.getFullYear() - 1 : now.getFullYear(),
now.getDate() - 1 === 0 ? now.getMonth() - 1: now.getMonth(),
now.getDate() - 1);
其他回答
令人惊讶的是,没有答案指向最简单的跨浏览器解决方案
找到昨天的同一时间*:
var yesterday = new Date(Date.now() - 86400000); // that is: 24 * 60 * 60 * 1000
*:如果您的用例不介意日历的不精确(如夏令时),那么这个方法很有效,否则我建议使用https://moment.github.io/luxon/
排在第二的法比亚诺和其他一些人已经给出了类似的答案,但这样做会让事情看起来更明显。
86400000 =一天中的毫秒
const event = new Date(); console.log(new Date(Date.parse(event) - 86400000)) console.log(事件)
下面是一个一行程序,用于在文本中获取YYYY-MM-DD格式的昨天日期并处理时区偏移。
new Date(Date.now() - 1 * 864e5 - new Date(Date.now() - 1 * 864e5).getTimezoneOffset() * 6e4).toISOString().split('T')[0]
它显然可以改变为返回日期,x天以前。包括时间等。
console.log(日期()) console.log(new Date(Date.now() - 1 * 864e5 - new Date(Date.now() - 1 * 864e5).getTimezoneOffset() * 6e4).toISOString().split('T')[0]);/ /“2019-11-11” console.log(new Date(Date.now() - 1 * 864e5 - new Date(Date.now() - 1 * 864e5). gettimezoneoffset () * 6e4). toisostring ().split('.')[0]. log .log(new Date(Date.now() - 1 * 864e5)替换(' T ', ' '));// "2019-11-11 11:11:11" // that is: [dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000 //这是:[dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000
d.setHours(0,0,0,0);
会成功的
我使用矩库,它非常灵活,易于使用。
在你的情况下:
let yesterday = moment().subtract(1, 'day').toDate();