用JavaScript计算昨天的日期

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

359709 次浏览

试试这个

var d = new Date();
d.setDate(d.getDate() - 1);
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)
//Create a date object using the current time
var now = new Date();


//Subtract one day from it
now.setDate(now.getDate()-1);

(2022年4月): 下面是一个片段扩展Date原型(而不会污染全局名称空间)

[2020年9月编辑]:包含前一个答案的代码片段,并添加了一个箭头函数。

// a (not very efficient) oneliner
let yesterday = new Date(new Date().setDate(new Date().getDate()-1));
console.log(`Yesterday (oneliner)\n${yesterday}`);


// a function call
yesterday = ( function(){this.setDate(this.getDate()-1); return this} )
.call(new Date);
console.log(`Yesterday (function call)\n${yesterday}`);


// an iife (immediately invoked function expression)
yesterday = function(d){ d.setDate(d.getDate()-1); return d}(new Date);
console.log(`Yesterday (iife)\n${yesterday}`);


// oneliner using es6 arrow function
yesterday = ( d => new Date(d.setDate(d.getDate()-1)) )(new Date);
console.log(`Yesterday (es6 arrow iife)\n${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(`Yesterday (method)\n${getYesterday()}`);
console.log(`Yesterday (method dateOnly=true)\n${getYesterday(true)}`);


// use Date.now
console.log(`Yesterday, using Date.now\n${new Date(Date.now() - 864e5)}`);
.as-console-wrapper {
max-height: 100% !important;
}

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

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

会成功的

为了概括问题并使用其他差异计算:

var yesterday = new Date((new Date()).valueOf() - 1000*60*60*24);

这将创建一个基于“now”值的新date对象,该值为整数,表示Unix epoch(单位为毫秒减去一天)。

两天前:

var twoDaysAgo = new Date((new Date()).valueOf() - 1000*60*60*24*2);

一小时前:

var oneHourAgo = new Date((new Date()).valueOf() - 1000*60*60);

令人惊讶的是,没有答案指向最简单的跨浏览器解决方案

找到昨天的同一时间*:

var yesterday = new Date(Date.now() - 86400000); // that is: 24 * 60 * 60 * 1000

*:如果你的用例不介意日历怪异的潜在不精确(如夏令时),这工作得很好,否则我建议使用https://moment.github.io/luxon/

试一试,对我有用:

var today = new Date();
var yesterday = new Date(today.setDate(today.getDate() - 1)); `

这让我得到了一个日期对象回来为昨天

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

(另见< >强这个小提琴< / >强)

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

在你的情况下:

let yesterday = moment().subtract(1, 'day').toDate();

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

获取当前时间的昨天日期 moment().subtract(1, 'days').toString() < / p >

获取以日期开头的昨天日期 moment().subtract(1, 'days').startOf('day').toString() < / p >

new Date(new Date().setDate(new Date().getDate()-1))

"Date.now() - 86400000"在夏令时结束日(当天有25小时)不起作用

另一个选择是使用Closure:

var d = new goog.date.Date();
d.add(new goog.date.Interval(0, 0, -1));

var today = new Date();
var yesterday1 = new Date(new Date().setDate(new Date().getDate() - 1));
var yesterday2 = new Date(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("Today: "+today);
console.log("Yesterday: "+yesterday1);
console.log("Yesterday: "+yesterday2);
console.log("Yesterday: "+yesterday3);
console.log("Yesterday: "+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(Date())
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].replace('T',' ')); // "2019-11-11 11:11:11"


// that is: [dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000    // this is: [dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000

解决边界日期问题(2020,01,01)-> 2019,12,31

var now = new Date();
return new Date(now.getMonth() - 1 === 0 ? now.getFullYear() - 1 : now.getFullYear(),
now.getDate() - 1 === 0 ? now.getMonth() - 1: now.getMonth(),
now.getDate() - 1);

排在第二的法比亚诺和其他一些人已经给出了类似的答案,但这样做会让事情看起来更明显。

86400000 =一天中的毫秒

const event = new Date();
console.log(new Date(Date.parse(event) - 86400000))
console.log(event)

我想要类似这个答案的东西:

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 = (date) => new Date(new Date(date).setDate(date.getDate() - 1));

我将其扩展为addDaysaddMonths函数:

/**
* 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