Así que selecciono dos fechas y construyo una matriz basada en esto.
Por ejemplo:
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));Esto devuelve (lista de días) lo siguiente:
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) {}Esto es correcto. Sin embargo, cuando construyo estas fechas:
const thesedays = daylist.map((v) => v.toISOString().slice(0, 10));Esto devuelve (estos días) lo siguiente:
0: "2022-03-30" 1: "2022-03-31" 2: "2022-04-01" 3: "2022-04-02" 4: "2022-04-03" 5: "2022-04-04"Por lo tanto, en realidad se usa el día anterior (30 de marzo en lugar de 31 y 4 de abril en lugar de 5)
Es la constante de estos días lo que necesito ajustar... pero no estoy seguro de cómo hacerlo.
se me ocurren dos formas...
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);o
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)El primer código estaría mejor con una función de ayuda
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);