[英]Divide the date range given by moment js by weeks
我想將給定的日期范圍划分為幾個月。 我想將這些月份按周分開。 我想以 7 天的間隔獲取從開始日期到月底的日期。 例如:(如 15/12/2020、22/12/2020、29/12/2020 -newMonth- 05/01/2020)
這種解釋很難理解。 畢竟我想像這樣創建一個 json。
開始日期:15/11/2020 - 結束日期:20/01/2021
[
{
"dates": [
15, // Starting date(15/11/2020)
22, // 1 week later
29 // 1 week later
],
"firstDay": "15/11/2020"
},
{
"dates": [
6,
13,
20,
27
],
"firstDay": "06/12/2020"
},
{
"dates": [
3,
10,
17
],
"firstDay": "03/01/2021"
}
]
您可以使用一些技巧來創建所需的數組結構:
while
循環保持current
日期不斷增加 7 天,以便與end
日期進行比較。 current
日期應使用循環開始時的start
日期進行初始化。month + year
組合作為鍵,這樣如果您的日期范圍跨越多年,您就不會將不同年份的月份折疊到同一個條目中。 對於while
循環的每次迭代,您從當前日期構造鍵,然后檢查該鍵是否存在於您的字典中。 如果沒有,那么我們可以將這個 object 推送到您的字典中:
{
dates: [currentDate],
firstDate: currentDate
}
如果它已經存在,那么您只需將日期推送到子對象的dates
數組中。
最后,要將您的字典轉換為您想要的數組結構,使用 ES6 Object.values()
將起作用。 請參閱下面的概念驗證:
function generateRanges(startDate, endDate) { let current = moment(startDate, 'DD/MM/YYYY'); const end = moment(endDate, 'DD/MM/YYYY'); // A dictionary to track unique month+year combinations const daysByMonth = {}; while (current < end) { // Construct key based on month+year const key = `${current.month()}${current.year()}`; const date = current.date(); // If key already exists, then we push into the `dates` array if (key in daysByMonth) { daysByMonth[key].dates.push(date); } // Otherwise we construct a brand new sub-object else { daysByMonth[key] = { dates: [date], // Since this is the first time we encounter the key, // We can assume this is the earliest/first date of the month firstDate: current.format('DD/MM/YYYY') } } // At the end of the while loop, increment by a week, rinse and repeat current.add(7, 'days'); } // Once done, we only want the values in the dictionary // We don't need to keep the unique month+year key return Object.values(daysByMonth); } const range = generateRanges('15/11/2020', '20/01/2021'); console.log(range);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
在處理日期或日期時間時,使用毫秒總是一個好習慣。 它還節省空間,長 integer = 4kb 而不是 Date() object 32 字節。
在您的情況下,將我們的日期轉換為毫秒非常簡單,找到 integer 之間的周數,然后通過此迭代運行循環增量。
let from = new Date('2020/11/15').getTime();
let to = new Date('2021/01/20').getTime();
let week = 604800000;
let day = 86400000;
let allWeeks = [];
let current =0;
let weeks = (to-from)/day/7
for (i=0; i<weeks; i++){
allWeeks.push(new Date(from += week).toLocaleDateString())
}
console.log(JSON.stringify(allWeeks))
//["22/11/2020","29/11/2020","06/12/2020","13/12/2020","20/12/2020","27/12/2020","03/01/2021","10/01/2021","17/01/2021","24/01/2021"]
最后,您將有一個適用於 JSON 的列表來構建您喜歡的任何邏輯。
我希望為您的案例指出不同的方法!
Moment.JS 有一個 API 用於向日期添加天數:添加function。
為了構建最終的 object,您將從 startDate 開始,並為每個循環迭代添加 7 天,直到到達結束日期。 像這樣:
let currentDate = moment(startDate);
while(currentDate < endDate) { // Make sure endDate is also a moment object
// Add the current date - you will want to adapt this
dates.push(currentDate.clone()); // Since .add() will mutate the currentDate object, clone the object when adding it to the array so that it's not affected by the add()
// Prepare for the next iteration
currentDate.add({days: 7});
}
至於月份更改,請記住每次迭代的最后一個月(使用月份)並在最終數組中創建一個新的 object,然后將日期添加到 object 而不是上一個。
旁注:月份在 Javascript 中為零索引,而月份日期(日期)不是這種情況
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.