UNPKG

@jk-core/components

Version:
46 lines (38 loc) 1.37 kB
const getWeeksInMonth = (viewDate:Date) => { const startOfMonth = new Date(viewDate.getFullYear(), viewDate.getMonth(), 1); const endOfMonth = new Date(viewDate.getFullYear(), viewDate.getMonth() + 1, 0); const weeks = []; let currentWeek = []; const startDayOfWeek = startOfMonth.getDay(); if (startDayOfWeek !== 0) { const prevMonthEnd = new Date(startOfMonth); prevMonthEnd.setDate(0); for (let i = startDayOfWeek - 1; i >= 0; i -= 1) { const prevDate = new Date(prevMonthEnd); prevDate.setDate(prevMonthEnd.getDate() - i); currentWeek.push({ thisMonth: 'before', date: prevDate }); } } const currentDate = new Date(startOfMonth); while (currentDate <= endOfMonth) { currentWeek.push({ thisMonth: 'this', date: new Date(currentDate) }); if (currentDate.getDay() === 6) { weeks.push(currentWeek); currentWeek = []; } currentDate.setDate(currentDate.getDate() + 1); } const endDayOfWeek = endOfMonth.getDay(); if (endDayOfWeek !== 6) { for (let i = 1; i <= 6 - endDayOfWeek; i += 1) { const nextDate = new Date(endOfMonth); nextDate.setDate(endOfMonth.getDate() + i); currentWeek.push({ thisMonth: 'after', date: nextDate }); } } if (currentWeek.length > 0) { weeks.push(currentWeek); } return weeks; }; export default getWeeksInMonth;