我正在使用角材料日期选择器,但当我将鼠标悬停在星期日时,它会选择下周my datepicker。我想这是因为我使用以下选项将第一天更改为星期一
import { NativeDateAdapter } from '@angular/material/core';
export class CustomDateAdapter extends NativeDateAdapter {
override getFirstDayOfWeek(): number {
return 1;
}
}
我用来计算一周的范围的 typescript :
@Injectable()
export class FiveDayRangeSelectionStrategy<D> implements MatDateRangeSelectionStrategy<D> {
constructor(private _dateAdapter: DateAdapter<D>) {}
selectionFinished(date: D | null): DateRange<D> {
return this._createFiveDayRange(date);
}
createPreview(activeDate: D | null): DateRange<D> {
return this._createFiveDayRange(activeDate);
}
private _createFiveDayRange(date: D | null): DateRange<D> {
if (date) {
console.log(date)
const start = this._getMondayBefore(date);
const end = this._getSundayAfter(start);
return new DateRange<D>(start, end);
}
return new DateRange<D>(null, null);
}
private _getMondayBefore(date: D): D {
const dayOfWeek = this._dateAdapter.getDayOfWeek(date);
const daysToSubtract = dayOfWeek - (this._dateAdapter.getFirstDayOfWeek());
return this._dateAdapter.addCalendarDays(date, -daysToSubtract);
}
private _getSundayAfter(date: D): D {
const dayOfWeek = this._dateAdapter.getDayOfWeek(date);
const daysToAdd = 8 - dayOfWeek - this._dateAdapter.getFirstDayOfWeek();
return this._dateAdapter.addCalendarDays(date, daysToAdd);
}
}
@Component({
selector: 'app-browser',
templateUrl: './browser.component.html',
styleUrls: ['./browser.component.scss'],
providers: [
{
provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
useClass: FiveDayRangeSelectionStrategy,
},
],
})
和我的html:
<mat-form-field appearance="fill">
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [rangePicker]="picker">
<input matStartDate placeholder="Start date">
<input matEndDate placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
我试着改变daysToAdd
和daysToSubtract
,但这只是改变了范围。而不是事实上,它选择下周时,悬停在周日。有人知道如何得到它,使它选择当前的星期一到周日?
1条答案
按热度按时间zzwlnbp81#
下面是创建
_createCurrentWeekRange()
函数的方法:我从下表中推导出当天与同一周的星期一之间的天数差异:
| 星期几|与星期一的天数差(1)|
| - ------| - ------|
| 周日(0)|-6天|
| 周一(1)|0天|
| 周二(2)|-1天|
| 周三(3)|-2天|
| 周四(4)|-3天|
| 周五(5)|-4天|
| 周六(6日)|-5天|
这给了我们一个
daysDifference = -(dayOfWeek + 6) % 7
的公式。要计算同一周的星期天,那么就变成了在星期一的日期上加上6天的问题。如果要使事情更一般化,并且要考虑一周的第一天可以是星期一以外的另一天的情况,则公式变为
daysDifference = -(dayOfWeek + 7 - firstDayOfWeek) % 7
,如下表所示:然后,实现就变成了类似于: