所以我有这段代码可以给我日期 A 和日期 B 之间的日期,但它也显示了我不想要的时间。
这是我当前有效的代码:
function getDatesInRange(startDate, endDate) {
const date = new Date(startDate.getTime());
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));
我在网上看到有人说要用
return dates.split(" ")[0];
但它仍然返回时间。
如何只返回日期 (年、月、日) 而不是时间?
.toDateString()
:
function getDatesInRange(startDate, endDate) {
const date = new Date(startDate.getTime());
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).map(date => date.toDateString()));
将获取日期,映射它以仅查找“日期”(不是时间)和
console.log
它。
你可以使用矩库来格式化返回。 https://momentjs.com/
getDatesInRange(d1, d2).map(date => moment(data).format("YYYY-MM-DD"))