如何在JavaScript中计算昨天作为日期?


当前回答

你可以使用momentjs,它非常有用,你可以用这个库实现很多事情。

获取当前时间的昨天日期 时刻()。减去(1天).toString ()

以日期开头获取昨天的日期 时刻()。减去(1天).startOf(天).toString ()

其他回答

我使用矩库,它非常灵活,易于使用。

在你的情况下:

let yesterday = moment().subtract(1, 'day').toDate();
var date = new Date();

date ; //# => Fri Apr 01 2011 11:14:50 GMT+0200 (CEST)

date.setDate(date.getDate() - 1);

date ; //# => Thu Mar 31 2011 11:14:50 GMT+0200 (CEST)

这将产生昨天零点的分钟精确

var d = new Date();
d.setDate(d.getDate() - 1);
d.setTime(d.getTime()-d.getHours()*3600*1000-d.getMinutes()*60*1000);

你可以使用momentjs,它非常有用,你可以用这个库实现很多事情。

获取当前时间的昨天日期 时刻()。减去(1天).toString ()

以日期开头获取昨天的日期 时刻()。减去(1天).startOf(天).toString ()

如果你既想获取昨天的日期,又想将日期格式化为人类可读的格式,可以考虑创建一个自定义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));

(也可以参看这把小提琴)