所以我選擇了兩個日期并基于此構建一個陣列。
例如:
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));
這將回傳(日程表)以下內容:
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 日)
這是我需要調整的這些天的常量......只是不確定如何?
uj5u.com熱心網友回復:
我可以想到兩種方法...
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456829.html
標籤:javascript 反应 日期
