getMonthTable.ts 2.5 KB

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