[英]Moment.js - How to get weekly data [startDate & endDate of each week] for given month excluding previous and next month date
For August 2020 I need data like this: - As per https://www.epochconverter.com/weeks/2020对于 2020 年 8 月,我需要这样的数据: - 根据https://www.epochconverter.com/weeks/2020
Week 31 - 2020-08-01 to 2020-08-02
Week 32 - 2020-08-03 to 2020-08-09
Week 33 - 2020-08-10 to 2020-08-16
Week 34 - 2020-08-17 to 2020-08-23
Week 35 - 2020-08-24 to 2020-08-30
Week 35 - 2020-08-31 to 2020-08-31
As per this info根据这个信息
This should work when we pass a year and month to a function as it should be generic当我们将一年和一个月传递给 function 时,这应该可以工作,因为它应该是通用的
Required output需要 output
weekNumbers = ["Week 31", "Week 32", "Week 33", "Week 34", "Week 35", "Week 36"]; // week number should not start from 1. it should be continuos from last year.
weekList = []; // this should contain start and end date for each week
Thank you in advance先感谢您
Common variables used:常用变量:
const monthIndex = 8; // give month index const year = 2020; // give year here
Code to get week numbers of month: -获取月份周数的代码:-
const getWeekNumbers = (year, month) => { let firstWeek = moment(new Date(year, month, 1)).isoWeek(); let lastWeek = moment(new Date(year, month + 1, 0)).isoWeek(); let out = [`Week ${firstWeek}`]; if (firstWeek === 52 || firstWeek === 53) { firstWeek = 0; } for (let i = firstWeek + 1; i <= lastWeek; i++) { out.push(`Week ${i}`); } return out; };
Code for getting week list data for month: -获取月份周列表数据的代码:-
function getMomentDate(start, end) { return { startDate: moment([2020, monthIndex - 1, start]), endDate: moment([2020, monthIndex - 1, end]) } } function weeks (month) { const weekStartEndDay = []; const first = month.day() == 0? 6: month.day()-1; let day = 7-first; const last = month.daysInMonth(); const count = (last-day)/7; weekStartEndDay.push(getMomentDate(1, day)); for (let i=0; i < count; i++) { weekStartEndDay.push(getMomentDate((day+1), (Math.min(day+=7, last)))); } return weekStartEndDay; }
Calling and getting output: -调用并获取 output:-
const month = moment([year, monthIndex - 1]) const weekNumbers = getWeekNumbers(year, monthIndex - 1); const weekList = weeks(month); console.log("weekNumbers", weekNumbers); console.log("weekList", weekList); weekList.forEach(date => { console.log("start - " + date.startDate.format('YYYY-MM-DD'), "\nend - " + date.endDate.format('YYYY-MM-DD')); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.