如何在JavaScript中计算昨天作为日期?
当前回答
new Date(new Date().setDate(new Date().getDate()-1))
其他回答
解决边界日期问题(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);
d.setHours(0,0,0,0);
会成功的
为了概括问题并使用其他差异计算:
var yesterday = new Date((new Date()).valueOf() - 1000*60*60*24);
这将创建一个基于“now”值的新date对象,该值为整数,表示Unix epoch(单位为毫秒减去一天)。
两天前:
var twoDaysAgo = new Date((new Date()).valueOf() - 1000*60*60*24*2);
一小时前:
var oneHourAgo = new Date((new Date()).valueOf() - 1000*60*60);
如果你既想获取昨天的日期,又想将日期格式化为人类可读的格式,可以考虑创建一个自定义DateHelper对象,看起来像这样:
var DateHelper = { addDays : function(aDate, numberOfDays) { aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays return aDate; // Return the date }, format : function format(date) { return [ ("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes ("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes date.getFullYear() // Get full year ].join('/'); // Glue the pieces together } } // With this helper, you can now just use one line of readable code to : // --------------------------------------------------------------------- // 1. Get the current date // 2. Subtract 1 day // 3. Format it // 4. Output it // --------------------------------------------------------------------- document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), -1));
(也可以参看这把小提琴)
//Create a date object using the current time
var now = new Date();
//Subtract one day from it
now.setDate(now.getDate()-1);