2 回答
TA贡献1851条经验 获得超4个赞
似乎你想做这样的事情(在伪代码中):
let obj = {
today: new Date(),
yesterday: today - 1 day,
tomorrow: today + 1 day
};
您设置今天的任何值的位置以及昨天和今天都会相应地更新。
您可以使用 getter 执行此操作,以便获取昨天和明天的值会根据今天的值计算它们。
例如:
let obj = {
get yesterday() {
if (this.today != undefined) {
let d = new Date(this.today);
d.setDate(d.getDate() - 1);
return d;
} else {
return void 0;
}
},
get tomorrow() {
if (this.today != undefined) {
let d = new Date(this.today);
d.setDate(d.getDate() + 1);
return d;
} else {
return void 0;
}
}
};
// Initial values
console.log('Yesterday: ' + obj.yesterday)
console.log('Today : ' + obj.today)
console.log('Tomorrow : ' + obj.tomorrow)
// Set today
obj.today = new Date();
// Get values
console.log('Yesterday: ' + obj.yesterday.toDateString());
console.log('Today : ' + obj.today.toDateString());
console.log('Tomrrow : ' + obj.tomorrow.toDateString());
TA贡献1982条经验 获得超2个赞
我个人不会为这种功能扩展原型而烦恼。您也可以在日期对象周围有一个包装器,该对象根据您最初发送的日期处理任何计算。
然后,可以使用此日期来获取相对于原始日期的下一个或上一个周期。
我添加了我的意思的一个片段,它为您提供了一种简单的方法来确定您最初要求的日期,以及它的付款日期。付款的结束期将是下一个期间的开始日期减去1天。
// from: https://stackoverflow.com/a/7751977/3231537
const twoWeeks = 12096e5;
// from: https://gist.github.com/dblock/1081513
var weekOfYear = function(date){
var d = new Date(+date);
d.setHours(0,0,0);
d.setDate(d.getDate()+4-(d.getDay()||7));
return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
};
class PayDateHelper {
constructor( date ) {
this._date = date;
}
nextPayPeriod() {
return new PayDateHelper( new Date( this.currentDate.getTime() + twoWeeks ) );
}
previousPayPeriod() {
return new PayDateHelper( new Date( this.currentDate.getTime() - twoWeeks ) );
}
get currentDate() {
return this._date;
}
get payDate() {
let interval = 0;
// when we are in an even week, subtract 7 days
if ( weekOfYear( this.currentDate ) % 2 === 0 ) {
interval += 7;
}
// and substract the days of the week back to 1 (monday)
interval += (this.currentDate.getDay() - 1);
const date = new Date( this.currentDate );
date.setDate( date.getDate() - interval );
return date;
}
}
console.log('-- current period');
let helper = new PayDateHelper( new Date() );
console.log( helper.currentDate );
console.log( helper.payDate );
console.log('-- next period');
let nextPeriod = helper.nextPayPeriod();
console.log( nextPeriod.currentDate );
console.log( nextPeriod.payDate );
console.log('-- previous period');
let previousPeriod = helper.previousPayPeriod();
console.log( previousPeriod.currentDate );
console.log( previousPeriod.payDate );
添加回答
举报