我试图借助JS瞬间创建一个自定义的日期选择器。 当年份改变时,我无法获得正确月份的日期的问题
getDaysArrayByMonth()
仅返回2018年的月份
public selectedMonth: any
private monthIterator = 0
public daysOfSelectedMonth = [];
public monthDaysAmount: number
onNextMonth() {
this.monthIterator++
this.selectedMonth = moment().add(this.monthIterator, 'months').format('MMMM YYYY');
this.getDaysArrayByMonth()
}
onPreviousMonth() {
this.monthIterator--
this.selectedMonth = moment().add(this.monthIterator, 'months').format('MMMM YYYY');
this.getDaysArrayByMonth()
}
getDaysArrayByMonth(){
this.daysOfSelectedMonth = []
this.monthDaysAmount = moment().month(this.selectedMonth).daysInMonth() ;
const remainingToEvenRows = 35 - this.monthDaysAmount
const days = this.monthDaysAmount + remainingToEvenRows
for (let i = 0; i < days; i++) {
this.daysOfSelectedMonth.push(moment().month(this.selectedMonth).date(i + 1).format('Do MMMM YYYY'));
}
}
答案 0 :(得分:0)
this.selectedMonth将保存月份和年份,因此您应该在瞬间构造函数中使用结果:
moment(this.selectedMonth, 'MMMM YYYY')
this.monthDaysAmount = moment(this.selectedMonth, 'MMMM YYYY').daysInMonth() ;
for (let i = 0; i < days; i++) {
this.daysOfSelectedMonth.push(moment(this.selectedMonth, 'MMMM YYYY').date(i + 1).format('Do MMMM YYYY'));
}
答案 1 :(得分:0)
moment()
函数始终返回当前日期,因此,如果您要在其上构建逻辑,它将始终返回当前月份和年份。因此您必须在构造函数中指定年份和月份,以返回所需/过去的月份。
因此,请按以下方式更改此代码
/// public selectedMonth: any
private monthIterator = 0
public daysOfSelectedMonth = [];
public monthDaysAmount: number
onNextMonth() {
this.monthIterator++
/// this.selectedMonth = moment().add(this.monthIterator, 'months').format('MMMM YYYY');
this.getDaysArrayByMonth(moment("201501", "YYYYMM").add(1, 'months').format('YYYYMM'));
}
onPreviousMonth() {
this.monthIterator--
/// this.selectedMonth = moment().add(this.monthIterator, 'months').format('MMMM YYYY');
this.getDaysArrayByMonth(moment("201501", "YYYYMM").add(1, 'months').format('YYYYMM'))
}
getDaysArrayByMonth(yearMonth: string){
this.daysOfSelectedMonth = []
/// this.monthDaysAmount = moment().month(this.selectedMonth).daysInMonth() ;
this.monthDaysAmount = moment(yearMonth,'YYYYMM').daysInMonth() ;
const remainingToEvenRows = 35 - this.monthDaysAmount
const days = this.monthDaysAmount + remainingToEvenRows
for (let i = 0; i < days; i++) {
this.daysOfSelectedMonth.push(moment().month(this.selectedMonth).date(i + 1).format('Do MMMM YYYY'));
}
}
请删除硬编码的201501
,并将YearMonth组合传递给函数onNextMonth
和onPreviousMonth
。
选中此stackblitz