Javascript 日期提前一天(前一天)

Javascript Date out by one day (the day before)

所以我 select 两个日期并以此为基础构建一个数组。

例如:

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));

此returns(日程表)以下:

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));

这个returns(这些天)以下:

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);