日期选择器BUG排查:30/31号当前日期误判为晚于结束日期
问题原因及解决方案
核心原因
你代码里的currentDate和endDate是DD/MM/YYYY格式的字符串,直接用>或==做比较时,是按字符串的字典序(字符逐个对比)判断大小,而非实际日期的先后逻辑:
- 比如当前日期是
30/10/2024,结束日期是01/11/2024,字符串比较时第一个字符3>0,会被判定为currentDate > endDate,但实际10月30日早于11月1日。 - 同理,31号的字符串开头也是
3,和任何下月初的日期字符串对比都会出现同样误判。
修复方案
不要用格式化后的字符串做日期比较,改用日期对象(Date或Moment)直接比较:
修改TypeScript代码
// 保留日期对象,不转成字符串 const currentDate = UtilsService.convertToDateIfMomentObject(new Date()); const endDate = UtilsService.convertToDateIfMomentObject(event.endDate); if (endDate) { // 直接比较日期对象的时间戳 if (currentDate.getTime() >= endDate.getTime()) { this.toastr.error("EOP Date must be greater than current Date",'',TOASTR_TIMEOUT); this.dateRangeProductionController.setValue(''); } }
如果convertToDateIfMomentObject返回的是Moment对象,也可以用Moment自带的比较方法:
if (currentDate.isSameOrAfter(endDate)) { this.toastr.error("EOP Date must be greater than current Date",'',TOASTR_TIMEOUT); this.dateRangeProductionController.setValue(''); }
这样就能基于实际日期时间逻辑判断,不会再出现30/31号的误判问题。
内容的提问来源于stack exchange,提问作者web_in
相关产品推荐
相关产品推荐

