這段代碼給了我過去 3 個月的日子,但我想嘗試優化它,如果可能的話讓它更快。
你能給我一些建議嗎?
<script type="module">
import {DateTime} from 'https://unpkg.com/[email protected]/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>
經過幾次嘗試,我得到了這個,你怎么看?
<script type="module">
import {DateTime} from 'https://unpkg.com/[email protected]/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>
uj5u.com熱心網友回復:
您可以通過不使用 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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/451460.html
標籤:javascript 日期 约会时间 时间 卢克森
