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)
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));
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);
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));
我将其扩展为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 })