使用discord.js与部落冲突API开发机器人时的JS日期解码问题
问题原因及修复方案:Discord机器人中Clash of Clans API日期解析失败
问题根源
你当前的日期处理逻辑存在两个核心问题:
- 错误的字符串截断:使用
slice(0, -8)处理原始日期字符串(如"20230422T185511.000Z")后,得到的是"20230422T18",这是完全不合法的日期格式,导致new Date()返回Invalid Date对象。调用getDate()、getMonth()等方法时,自然会返回NaN。 - 非标准ISO格式解析兼容性:Clash of Clans API返回的是紧凑格式的ISO字符串(无连字符
-和冒号:),部分JavaScript环境无法直接解析这种格式,这也是你最初使用toISOString()、toLocaleString()时出错的根本原因——因为Date对象本身就是无效的。
修复方案
方案1:手动拆分字符串构造标准ISO格式
编写工具函数,将紧凑格式的日期字符串转换为标准ISO格式,确保所有环境都能正确解析:
// 解析紧凑格式的ISO日期字符串 function parseCocDate(dateStr) { // 拆分日期和时间部分 const dateSegment = dateStr.slice(0, 8); const timeSegment = dateStr.slice(9, 15); // 拼接为标准ISO格式:YYYY-MM-DDTHH:mm:ss.sssZ const standardISO = `${dateSegment.slice(0,4)}-${dateSegment.slice(4,6)}-${dateSegment.slice(6,8)}T${timeSegment.slice(0,2)}:${timeSegment.slice(2,4)}:${timeSegment.slice(4,6)}.000Z`; return new Date(standardISO); } // 格式化日期为目标字符串格式 function formatDisplayDate(date) { return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; } // 测试代码 const preparationStartTime = "20230422T185511.000Z"; const prepStart = parseCocDate(preparationStartTime); const startTime = "20230423T175511.000Z"; const start = parseCocDate(startTime); const endTime = "20230424T175511.000Z"; const end = parseCocDate(endTime); console.log(`Prep Time: ${formatDisplayDate(prepStart)} \nStart Time: ${formatDisplayDate(start)}\nEnd Time: ${formatDisplayDate(end)}`);
方案2:正则表达式快速转换格式
用正则表达式自动补充分隔符,代码更简洁:
const formatDisplayDate = (date) => `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; const preparationStartTime = "20230422T185511.000Z"; // 正则替换为标准ISO格式 const standardDateStr = preparationStartTime.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/, '$1-$2-$3T$4:$5:$6'); const prepStart = new Date(standardDateStr); // 其他日期同理处理 console.log(`Prep Time: ${formatDisplayDate(prepStart)}`);
验证结果
两种方案执行后,都会输出正确的日期格式:
Prep Time: 22/4/2023 18:55:11 Start Time: 23/4/2023 17:55:11 End Time: 24/4/2023 17:55:11
内容的提问来源于stack exchange,提问作者0minutes
相关产品推荐
相关产品推荐

