Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
Js take the days of the last n months

This code gives me the days of the last 3 months, but I would like to try to optimize it, make it faster if possible.

Can you give me some advice?

<script type="module">
import {DateTime} from 'https://unpkg.com/luxon@2.3.1/src/luxon.js';
console.time('Time')

const lNow = DateTime.now()
const lThreeMonthsAgo = lNow.minus({ month: 3 }).startOf('week')
let lastDays = []
let ii = 0
while (
  Math.floor(lNow.diff(lThreeMonthsAgo.plus({ days: ii }), 'days').days) >= 0
) {
  lastDays.push(lThreeMonthsAgo.plus({ day: ii }))
  ii = ii + 1
}

console.timeEnd('Time')
console.log(lastDays)
</script>

After a few tries I got this, what do you think?

<script type="module">
import {DateTime} from 'https://unpkg.com/luxon@2.3.1/src/luxon.js';
console.time('Time')

const lNow = DateTime.now();
const lThreeMonthsAgo = lNow.minus({ month: 3 }).startOf("week");
let num = Math.ceil(lNow.diff(lThreeMonthsAgo, "days").days);
let lastDays = [...Array(num).keys()].reduce(
  (acc, val) => [...acc, lThreeMonthsAgo.plus({ day: val })],
  []
);

console.timeEnd('Time')
console.log(lastDays)
</script>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can possibly gain some speed by not using the luxon library, but just native Date objects:

let now = new Date();
let start = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate());
// If date "overflowed" into next month, then bring it back:
if ((start.getMonth() + 3) % 12 != now.getMonth()) {
     start.setDate(0); // Go to last day of previous month
}
// Go to previous Monday if not yet a Monday
start.setDate(start.getDate() - (start.getDay() + 6) % 7); 
let lastDays = [];
while (start < now) {
    lastDays.push(start.toLocaleDateString("en-SE")); // Format YYYY-MM-DD
    start.setDate(start.getDate() + 1); // Next day
}
console.log(lastDays);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!