utils.mjs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { createNamespace } from "../utils/index.mjs";
  2. const [name, bem, t] = createNamespace("calendar");
  3. const formatMonthTitle = (date) => t("monthTitle", date.getFullYear(), date.getMonth() + 1);
  4. function compareMonth(date1, date2) {
  5. const year1 = date1.getFullYear();
  6. const year2 = date2.getFullYear();
  7. if (year1 === year2) {
  8. const month1 = date1.getMonth();
  9. const month2 = date2.getMonth();
  10. return month1 === month2 ? 0 : month1 > month2 ? 1 : -1;
  11. }
  12. return year1 > year2 ? 1 : -1;
  13. }
  14. function compareDay(day1, day2) {
  15. const compareMonthResult = compareMonth(day1, day2);
  16. if (compareMonthResult === 0) {
  17. const date1 = day1.getDate();
  18. const date2 = day2.getDate();
  19. return date1 === date2 ? 0 : date1 > date2 ? 1 : -1;
  20. }
  21. return compareMonthResult;
  22. }
  23. const cloneDate = (date) => new Date(date);
  24. const cloneDates = (dates) => Array.isArray(dates) ? dates.map(cloneDate) : cloneDate(dates);
  25. function getDayByOffset(date, offset) {
  26. const cloned = cloneDate(date);
  27. cloned.setDate(cloned.getDate() + offset);
  28. return cloned;
  29. }
  30. function getMonthByOffset(date, offset) {
  31. const cloned = cloneDate(date);
  32. cloned.setMonth(cloned.getMonth() + offset);
  33. if (cloned.getDate() !== date.getDate()) {
  34. cloned.setDate(0);
  35. }
  36. return cloned;
  37. }
  38. function getYearByOffset(date, offset) {
  39. const cloned = cloneDate(date);
  40. cloned.setFullYear(cloned.getFullYear() + offset);
  41. if (cloned.getDate() !== date.getDate()) {
  42. cloned.setDate(0);
  43. }
  44. return cloned;
  45. }
  46. const getPrevDay = (date) => getDayByOffset(date, -1);
  47. const getNextDay = (date) => getDayByOffset(date, 1);
  48. const getPrevMonth = (date) => getMonthByOffset(date, -1);
  49. const getNextMonth = (date) => getMonthByOffset(date, 1);
  50. const getPrevYear = (date) => getYearByOffset(date, -1);
  51. const getNextYear = (date) => getYearByOffset(date, 1);
  52. const getToday = () => {
  53. const today = /* @__PURE__ */ new Date();
  54. today.setHours(0, 0, 0, 0);
  55. return today;
  56. };
  57. function calcDateNum(date) {
  58. const day1 = date[0].getTime();
  59. const day2 = date[1].getTime();
  60. return (day2 - day1) / (1e3 * 60 * 60 * 24) + 1;
  61. }
  62. export {
  63. bem,
  64. calcDateNum,
  65. cloneDate,
  66. cloneDates,
  67. compareDay,
  68. compareMonth,
  69. formatMonthTitle,
  70. getDayByOffset,
  71. getMonthByOffset,
  72. getNextDay,
  73. getNextMonth,
  74. getNextYear,
  75. getPrevDay,
  76. getPrevMonth,
  77. getPrevYear,
  78. getToday,
  79. getYearByOffset,
  80. name,
  81. t
  82. };