Angular8中ngx-hijri-gregorian-datepicker日期转换方法偶发失效
问题根因与修复方案
1. 直接错误:变量名大小写不匹配
Date2处理逻辑中存在变量名拼写错误:
if (this.selectedDateType === DateType.Hijri) { // 此处赋值给了小写开头的未声明变量date2 date2 = this.dateFormatterSev.ToGregorian(Date2); } // 后续读取的仍是大写开头的Date2,未拿到转换后的值 req.date2 = Date2.year + '-' + Date2.month + '-' + Date2.day;
大小写不匹配导致转换结果没有同步到后续使用的变量,是Date2逻辑失效的直接原因。
2. 潜在问题:未处理ToGregorian返回null的情况
ToGregorian方法偶发返回null时,直接访问null的year/month/day属性就会生成null-null-null的异常结果,需要补充空值防护逻辑。
修复后代码示例
// 构造函数注入 private dateFormatterSev: DateFormatterService // 业务逻辑 if (this.Date1) { let Date1 = JSON.parse(JSON.stringify(this.Date1)); if (this.selectedDateType === DateType.Hijri) { const converted = this.dateFormatterSev.ToGregorian(Date1); // 转换成功才覆盖原值,可根据业务需求调整降级逻辑 if (converted) Date1 = converted; } req.date1 = `${Date1.year}-${Date1.month}-${Date1.day}`; } if (this.Date2) { let Date2 = JSON.parse(JSON.stringify(this.Date2)); if (this.selectedDateType === DateType.Hijri) { // 修正变量名大小写问题 const converted = this.dateFormatterSev.ToGregorian(Date2); if (converted) Date2 = converted; } req.date2 = `${Date2.year}-${Date2.month}-${Date2.day}`; }
可选优化建议
- 若
ToGregorian频繁返回null,可打印入参排查是否为传入的回历日期格式不符合插件要求,比如特殊闰月日期、年份超出插件支持范围。 - 可统一封装日期转换公共方法,避免重复代码和变量名拼写错误。
内容的提问来源于stack exchange,提问作者Nishan Madhuwantha
相关产品推荐
相关产品推荐

