怎么样在JavaScript中把昨天作为一个日期进行计算?
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)
// a (not very efficient) oneliner let yesterday = new Date(new Date().setDate(new Date().getDate()-1)); console.log(yesterday); // a function call yesterday = ( function(){this.setDate(this.getDate()-1); return this} ) .call(new Date); console.log(yesterday); // an iife (immediately invoked function expression) yesterday = function(d){ d.setDate(d.getDate()-1); return d}(new Date); console.log(yesterday); // oneliner using es6 arrow function yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date); console.log(yesterday); // use a method const getYesterday = (dateOnly = false) => { let d = new Date(); d.setDate(d.getDate() - 1); return dateOnly ? new Date(d.toDateString()) : d; }; console.log(getYesterday()); console.log(getYesterday(true));
令人惊讶的是,没有答案指向最简单的跨浏览器解决方案
要找到与昨天完全相同的时间。
var yesterday = new Date(Date.now() - 86400000); // that is: 24 * 60 * 60 * 1000
如果你不介意潜在的日历怪异的不精确性(比如夏令时),这个方法很好用,否则我建议使用 https://moment.github.io/luxon/
找不到想要的答案?提一个您自己的问题。
0 声望
这家伙太懒,什么都没留下
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)
// a (not very efficient) oneliner let yesterday = new Date(new Date().setDate(new Date().getDate()-1)); console.log(yesterday); // a function call yesterday = ( function(){this.setDate(this.getDate()-1); return this} ) .call(new Date); console.log(yesterday); // an iife (immediately invoked function expression) yesterday = function(d){ d.setDate(d.getDate()-1); return d}(new Date); console.log(yesterday); // oneliner using es6 arrow function yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date); console.log(yesterday); // use a method const getYesterday = (dateOnly = false) => { let d = new Date(); d.setDate(d.getDate() - 1); return dateOnly ? new Date(d.toDateString()) : d; }; console.log(getYesterday()); console.log(getYesterday(true));
令人惊讶的是,没有答案指向最简单的跨浏览器解决方案
要找到与昨天完全相同的时间。
var yesterday = new Date(Date.now() - 86400000); // that is: 24 * 60 * 60 * 1000
你的答案