所以我选择两个日期,并在此基础上构建一个数组。
例如:
var getDaysArray = function (s, e) { for (var a = [], d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) { a.push(new Date(d)); } return a; };
var daylist = getDaysArray(new Date(datefrom), new Date(dateto));
这将返回(daylist(以下内容:
0: Thu Mar 31 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
1: Fri Apr 01 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
2: Sat Apr 02 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
3: Sun Apr 03 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
4: Mon Apr 04 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
5: Tue Apr 05 2022 00:00:00 GMT+0800 (Australian Western Standard Time) {}
这是正确的。然而,当我构建这些日期时:
const thesedays = daylist.map((v) => v.toISOString().slice(0, 10));
这将返回(这些天(以下内容:
0: "2022-03-30"
1: "2022-03-31"
2: "2022-04-01"
3: "2022-04-02"
4: "2022-04-03"
5: "2022-04-04"
所以它实际上是在使用前一天(3月30日而不是31日,4月4日而不是5日(
这是这些天我需要调整的心情。。。只是不知道怎么做?
我可以想出两种方法。。。
const daylist = [
new Date("2022-01-15T00:00:00"),
new Date("2022-02-15T00:00:00"),
new Date("2022-03-15T00:00:00"),
];
const thesedays = daylist.map((v) =>
`${
v.getFullYear().toString().padStart(4, "0")
}-${
(v.getMonth() + 1).toString().padStart(2, "0")
}-${
v.getDate().toString().padStart(2, "0")
}`
);
console.log(thesedays);
或
const daylist = [
new Date("2022-01-15T00:00:00"),
new Date("2022-02-15T00:00:00"),
new Date("2022-03-15T00:00:00"),
];
const thesedays = daylist.map(
(v) =>
new Date(
Date.parse(
new Intl.DateTimeFormat("fr-CA", {
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(v)
)
).toISOString().split("T")[0]
);
console.log(thesedays)
第一个代码最好有一个辅助功能
const daylist = [
new Date("2022-01-15T00:00:00"),
new Date("2022-02-15T00:00:00"),
new Date("2022-03-15T00:00:00"),
];
const zf = (n, z=2) => n.toString().padStart(z, '0');
const thesedays = daylist.map((v) =>
`${zf(v.getFullYear(), 4)}-${zf((v.getMonth() + 1))}-${zf(v.getDate())}`
);
console.log(thesedays);