如何在JavaScript中计算昨天作为日期?
当前回答
这里有2个一句话:
new Date(new Date().setHours(-1))
new Date(Date.now() - 86400000)
其他回答
"Date.now() - 86400000"在夏令时结束日(当天有25小时)不起作用
另一个选择是使用Closure:
var d = new goog.date.Date();
d.add(new goog.date.Interval(0, 0, -1));
我想要这样的答案:
const yesterday = d => new Date(d.setDate(d.getDate() - 1));
问题是它突变了d,所以让我们把突变藏在里面。
const yesterday = (date) => {
const dateCopy = new Date(date);
return new Date(dateCopy.setDate(dateCopy.getDate() - 1));
}
我们可以将其分解为一行表达式,但它变得有点难以阅读:
const yesterday = d => new Date(new Date(d).setDate(d.getDate() - 1));
我将其扩展为addDays和addMonths函数:
/** * Add (or subtract) days from a date * * @param {Number} days * @returns {Function} Date => Date + days */ const addDays = (days) => (date) => new Date(new Date(date).setDate(date.getDate() + days)); /** * Add (or subtract) months from a date * * @param {Number} months * @returns {Function} Date => Date + months */ const addMonths = (months) => (date) => new Date(new Date(date).setMonth(date.getMonth() + months)); // We can recreate the yesterday function: const yesterday = addDays(-1) // note that `now` doesn't get mutated const now = new Date(); console.log({ now, yesterday: yesterday(now) }) const lastMonth = addMonths(-1)(now); console.log({ now, lastMonth }) .as-console-wrapper { max-height: 100% !important; }
但在这一点上,你可能想开始使用date-fns addDays。
这将产生昨天零点的分钟精确
var d = new Date();
d.setDate(d.getDate() - 1);
d.setTime(d.getTime()-d.getHours()*3600*1000-d.getMinutes()*60*1000);
//Create a date object using the current time
var now = new Date();
//Subtract one day from it
now.setDate(now.getDate()-1);
排在第二的法比亚诺和其他一些人已经给出了类似的答案,但这样做会让事情看起来更明显。
86400000 =一天中的毫秒
const event = new Date(); console.log(new Date(Date.parse(event) - 86400000)) console.log(事件)