这是我的控制者:
private day: any = '';
private add: number = 0;
private remove: number = 0;
private days: any = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
dayBefore() {
let now = new Date();
this.remove += 1;
let newDate = this.decrementDays(now, this.remove);
this.day = this.days[newDate.getDay()];
}
dayAfter() {
let now = new Date();
this.add += 1;
let newDate = this.incrementDays(now, this.add);
this.day = this.days[newDate.getDay()];
}
dayToday() {
let now = new Date();
this.day = this.days[now.getDay()];
this.add = 0;
this.remove = 0;
}
decrementDays: any = function removeDay(date: any, days: any) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() - days, date.getHours(), date.getSeconds(), date.getMilliseconds());
};
incrementDays: any = function addDay(date: any, days: any) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, date.getHours(), date.getSeconds(), date.getMilliseconds());
};
HTML:
<ul>
<li (click)="dayBefore()"></li>
<li (click)="dayToday()"></li>
<li (click)="dayAfter()"></li>
</ul>
<span>{{day}}</span>
这个问题是,虽然增量和减量有效,但是当我想在dayBefore()
之后转到dayAfter()
时,我不会立即转到前一天的日期。
如果我点击dayAfter()
,当我点击Tuesday
时,我会Monday
(如果今天是and
)dayBefore()
在Sunday
,而不是星期一。我怎么能解决这个问题?我知道为什么会这样。这是因为它从今天的日期(Monday
)开始计算,而不是从我停止它的地方算起。
谢谢你们。
答案 0 :(得分:1)
试试这个:
private day: any = '';
private add: number = 0;
private remove: number = 0;
private days: any = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
private today = new Date();
dayBefore() {
let newDate = this.decrementDays(1);
this.day = this.days[newDate.getDay()];
}
dayAfter() {
let newDate = this.incrementDays(1);
this.day = this.days[newDate.getDay()];
}
dayToday() {
this.today = new Date();
this.day = this.days[this.today.getDay()];
}
decrementDays: any = function removeDay(days: any) {
let date = this.today;
this.today = new Date(date.getFullYear(), date.getMonth(), date.getDate() - days, date.getHours(), date.getSeconds(), date.getMilliseconds());
return this.today;
};
incrementDays: any = function addDay(days: any) {
let date = this.today;
this.today = new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, date.getHours(), date.getSeconds(), date.getMilliseconds());
return this.today;
};
这可以进一步重构,并且可以更简单。我刚刚做了一个快速修复。
答案 1 :(得分:1)
@Component({
// boilerplate and ceremony
})
export class DayOfWeekComponent {
days = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
];
dayOfWeek = new Date().getDay();
resetDayOfWeek() {
this.dayOfWeek = new Date().getDay();
}
offsetDayOfWeek(offset: number) {
let dayOfWeek = (this.dayOfWeek + offset) % 7;
if (dayOfWeek < 0) {
dayOfWeek += 7;
}
this.dayOfWeek = dayOfWeek;
}
}
模板:
<ul>
<li (click)="offsetDayOfWeek(-1)">Previous</li>
<li (click)="resetDayOfWeek()">Today</li>
<li (click)="offsetDayOfWeek(1)">Next</li>
</ul>
<span>{{days[dayOfWeek]}}</span>