如何修改JS代码生成从当日开始的连续8天动态日期范围用于HTML表格表头
修改后代码
dates() { const dates = [] // 生成共8天日期:当日 + 后续7天 for (let i = 0; i < 8; i++) { const tempDate = new Date() tempDate.setDate(tempDate.getDate() + i) // 格式化为 YYYY-MM-DD 格式 const formatDate = tempDate.toISOString().split('T')[0] dates.push(formatDate) } // 返回格式与原代码完全一致:升序排列的日期字符串数组 return dates },
说明
- 完全移除了原代码中依赖
this.rows对象提取日期的逻辑,直接动态生成日期序列,不需要依赖业务数据 - 返回值格式和原代码完全对齐,均为升序排列的
YYYY-MM-DD格式字符串数组,原有调用该方法渲染表头的逻辑不需要做任何改动 - 如果你需要使用本地时区的日期而非UTC时区日期,可以把格式化部分的代码替换为如下实现,避免时区差导致日期偏差:
const year = tempDate.getFullYear() const month = String(tempDate.getMonth() + 1).padStart(2, '0') const day = String(tempDate.getDate()).padStart(2, '0') const formatDate = `${year}-${month}-${day}`
内容的提问来源于stack exchange,提问作者Geoff_S
相关产品推荐
相关产品推荐

