JavaScript获取昨天的日期

what 发表于: 2021-08-25   最后更新时间: 2021-09-14 00:39:08   1,330 游览

怎么样在JavaScript中把昨天作为一个日期进行计算?

发表于 2021-08-25
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/

你的答案

查看javascript相关的其他问题或提一个您自己的问题