PrimeNG Calendar报错:Uncaught (in promise): Missing number at position 0
解决p-calendar绑定MongoDB日期格式的错误问题
我来帮你搞定这个日期绑定的问题!你遇到的Missing number at position 0错误,根源在于MongoDB返回的日期是嵌套的$date对象,而p-calendar无法直接识别这种结构,你之前的转换方式没抓到问题的核心,所以错误一直存在。
问题分析
你从MongoDB拿到的日期是这样的结构:
{ "$date": "2018-01-24T18:30:00.000Z" }
而p-calendar需要的是标准的Date对象或者能被Date构造函数直接解析的ISO格式字符串。你之前直接用new Date(post.fromDate)时,post.fromDate是个对象,不是字符串,Date构造函数无法解析这种对象,所以抛出了错误;转成UTCString的操作其实是多余的,反而可能让格式变得更难被组件识别。
正确的解决步骤
- 提取MongoDB日期中的ISO字符串:先从嵌套的
$date对象里取出真正的日期字符串值 - 转换为Date对象(或直接用ISO字符串):把提取到的ISO字符串转成Date对象,直接赋值给绑定的变量
代码示例
假设你从后端获取到的原始数据是:
const post = { toDate: { "$date": "2018-01-24T18:30:00.000Z" }, fromDate: { "$date": "2018-01-11T18:30:00.000Z" } };
处理日期并绑定的代码:
// 提取$date字段并转换为Date对象 productId.toDate = new Date(post.toDate.$date); productId.fromDate = new Date(post.fromDate.$date);
或者如果你不想转成Date对象,直接用ISO字符串也可以:
productId.toDate = post.toDate.$date; productId.fromDate = post.fromDate.$date;
进阶:统一处理工具函数
如果你的项目里有很多这种MongoDB日期需要处理,可以写个工具函数来复用:
function parseMongoDate(mongoDateObj) { // 先判断是否是MongoDB的日期结构 if (mongoDateObj && typeof mongoDateObj === 'object' && mongoDateObj.$date) { return new Date(mongoDateObj.$date); } // 如果已经是Date对象或字符串,直接返回 return mongoDateObj; } // 使用方式 productId.toDate = parseMongoDate(post.toDate); productId.fromDate = parseMongoDate(post.fromDate);
验证效果
处理完成后,productId.toDate和productId.fromDate会变成标准的Date对象(或ISO字符串),p-calendar就能正确识别并绑定,不会再出现Missing number at position 0的错误了。
内容的提问来源于stack exchange,提问作者phpdroid
相关产品推荐
相关产品推荐

