简体   繁体   English

js取最近n个月的天数

[英]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.这段代码给了我过去 3 个月的天数,但我想尝试优化它,如果可能的话让它更快。

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>

You can possibly gain some speed by not using the luxon library, but just native Date objects:您可以通过不使用 luxon 库而只使用本机 Date 对象来获得一些速度:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM