如何在JavaScript中计算昨天作为日期?
当前回答
var today = new Date(); var yesterday1 =新日期(新日期()。setDate(new Date().getDate() - 1)); var yesterday2 =新的日期(Date.now() - 86400000); var yesterday3 = new Date(Date.now() - 1000*60*60*24); var yesterday4 = new Date((new Date()).valueOf() - 1000*60*60*24); 今天console.log(“:“今天+); 昨天console.log(“:”+ yesterday1); 昨天console.log(“:”+ yesterday2); 昨天console.log(“:”+ yesterday3); 昨天console.log(“:”+ yesterday4);
其他回答
下面是一个一行程序,用于在文本中获取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
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)
这里有2个一句话:
new Date(new Date().setHours(-1))
new Date(Date.now() - 86400000)
我想要这样的答案:
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。
d.setHours(0,0,0,0);
会成功的