如何在JavaScript中获取两个日期之间仅含年月日的日期列表
你原来的代码返回的是Date对象数组,网上看到的dates.split(" ")[0]根本不适用——因为dates是数组,不是单个字符串,这就是为什么那方法没用。
要只返回年月日信息,分两种常见需求,下面是对应解决方案:
方案1:返回YYYY-MM-DD格式的字符串数组
修改push逻辑,把每个Date对象转成仅包含日期的字符串:
function getDatesInRange(startDate, endDate) { const date = new Date(startDate.getTime()); const dates = []; while (date <= endDate) { // 转成ISO字符串后截取日期部分,得到标准的YYYY-MM-DD格式 dates.push(date.toISOString().split('T')[0]); date.setDate(date.getDate() + 1); } return dates; } const d1 = new Date("2022-01-18"); const d2 = new Date("2022-01-24"); console.log(getDatesInRange(d1, d2)); // 输出:["2022-01-18", "2022-01-19", "2022-01-20", "2022-01-21", "2022-01-22", "2022-01-23", "2022-01-24"]
方案2:返回时间清零的Date对象
如果你需要保留Date对象,但不想带时间信息(即时间部分为00:00:00),可以在初始化时重置时间:
function getDatesInRange(startDate, endDate) { const date = new Date(startDate.getTime()); // 把起始日期的时间部分清零 date.setHours(0, 0, 0, 0); const dates = []; while (date <= endDate) { dates.push(new Date(date)); date.setDate(date.getDate() + 1); } return dates; } const d1 = new Date("2022-01-18"); const d2 = new Date("2022-01-24"); console.log(getDatesInRange(d1, d2)); // 输出的每个Date对象时间部分均为00:00:00
补充:自定义日期格式(如MM/DD/YYYY)
如果需要非标准格式,可以手动拼接年、月、日,注意给月份和日期补零:
function formatDate(date) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需+1后补零 const day = String(date.getDate()).padStart(2, '0'); return `${month}/${day}/${year}`; // 可按需调整格式 } function getDatesInRange(startDate, endDate) { const date = new Date(startDate.getTime()); const dates = []; while (date <= endDate) { dates.push(formatDate(date)); date.setDate(date.getDate() + 1); } return dates; }
内容的提问来源于stack exchange,提问作者laraCoder
相关产品推荐
相关产品推荐

