我正在使用fullcalendar-react,并且我有以下时间表,我在该时间表中尝试获取列表的最早时间,并删除关闭日期:
export default {
monday: {
startTime: '10:00',
endTime: '23:00'
},
tuesday: {
startTime: '08:00',
endTime: '00:00'
},
wednesday: {
startTime: '09:00',
endTime: '22:00'
},
thursday: {
startTime: '14:00',
endTime: '00:00'
},
friday: undefined,
saturday: {
startTime: '13:00',
endTime: '21:00'
},
sunday: undefined
}
要过滤关闭的日期并获得最早的时间,我正在处理filter和reduce,如下所示:
getOpeningHour() {
let value: any = "00:00:00";
if (this.props.schedule) {
const schedule = this.props.schedule; // the schedule I presented above
if (Object.keys(schedule).length >= 1) {
const minValue = Object.keys(schedule)
.filter((key) => schedule[key])
.map((key: string) => moment(schedule[key].startTime, 'HH:mm'))
.reduce((min: moment.Moment, value: moment.Moment) => (!min || value.isBefore(min) ? value : min), moment('00:00', 'HH:mm'));
// Gets the earliest hour when the list is not empty, but when I give midnight as default value, it's always midnight.
value = minValue.format('HH:mm:ss');
}
}
return value;
}
打开日历时,出现此错误:
未捕获的TypeError:减少没有初始值的空数组
当列表为空时,我尝试提供, moment('00:00', 'HH:mm')
作为默认值,但我想,这样,我的日历总是从午夜开始,而忽略其余时间。
-----编辑-----
代码实际上正在工作,并且由于午夜早于08:00,因此它将显示午夜。唯一的事情是仅在列表为空时显示午夜。
当我使用moment()小时时,如何解决此问题? 谢谢!
答案 0 :(得分:2)
尝试moment('24:00', 'HH:mm')
:
const hourTemplate = 'HH:mm';
const getEarliersHour = schedule =>
Object.values(schedule)
.filter(value => value) // no undefined
.map(time => moment(time.startTime, hourTemplate))
.reduce(
(min, curr) => (curr.isBefore(min) ? curr : min),
moment('24:00', hourTemplate) // latest moment
)
.format(hourTemplate);
getEarliersHour(schedule); // 08:00
getEarliersHour({}); // 00:00
演示: