getMonthTable.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. *
  3. * @param {string} month
  4. */
  5. import {
  6. startOfMonth,
  7. lastDayOfMonth,
  8. getDaysInMonth,
  9. // getDay,
  10. // parseISO,
  11. format
  12. } from 'date-fns';
  13. function formatFullDate(year: number | string = '', month: number | string = '', day: number | string = ''): string {
  14. let dateStr = '';
  15. const monthFull = typeof month === 'number' && month < 10 ? `0${ month}` : month.toString();
  16. const dayNumberFull = typeof day === 'number' && day < 10 ? `0${ day}` : day.toString();
  17. dateStr = `${String(year) }-${ monthFull }-${ dayNumberFull}`;
  18. return dateStr;
  19. }
  20. /**
  21. * [getWeeks description]
  22. */
  23. export type WeekStartNumber = 0 | 1 | 2 | 3 | 4 | 5 | 6;
  24. function getWeeks(date: Date, weekStartsOn: WeekStartNumber = 0) {
  25. const weekDayNotInMonth = {
  26. dayNumber: '',
  27. dateNumberFull: '',
  28. fullDate: '',
  29. }; // For the first or last week epmtyDays
  30. const daysInMonth = getDaysInMonth(date); // Get the total number of days in the month
  31. const year = format(date, 'yyyy');
  32. const month = format(date, 'MM');
  33. const lastday = lastDayOfMonth(date); // Get the last day of the month
  34. const firstDay = startOfMonth(date); // Get the first day of the month
  35. // Const firstDayInWeek = getDay (firstDay);//The first day belongs to the day of the week
  36. // What is the first day of the month in the first row?
  37. const firstDayInWeek = Number(format(firstDay, 'e', { weekStartsOn }));
  38. const weeks = [];
  39. let week = [];
  40. // add empty days to set first day in correct position
  41. for (let s = 1; s < firstDayInWeek; s++) {
  42. week.push(weekDayNotInMonth);
  43. }
  44. for (let d = 0; d < daysInMonth; d++) {
  45. const dayNumber = d + 1;
  46. const dayNumberFull = dayNumber < 10 ? `0${ dayNumber}` : dayNumber.toString();
  47. const fullDate = formatFullDate(year, month, dayNumber);
  48. week.push({
  49. dayNumber,
  50. dayNumberFull,
  51. fullDate,
  52. });
  53. if (week.length === 7) {
  54. weeks.push(week);
  55. week = [];
  56. } else if (fullDate === format(lastday, 'yyyy-MM-dd')) {
  57. // Last week alone
  58. weeks.push(week);
  59. week = [];
  60. }
  61. }
  62. return weeks;
  63. }
  64. const getMonthTable = (month: Date, weekStartsOn: WeekStartNumber) => {
  65. const weeks = getWeeks(month, weekStartsOn);
  66. const monthText = format(month, 'yyyy-MM');
  67. return { monthText, weeks, month };
  68. };
  69. export default getMonthTable;
  70. export { formatFullDate };