utils.mjs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. const getPrevDay = (date) => getDayByOffset(date, -1);
  31. const getNextDay = (date) => getDayByOffset(date, 1);
  32. const getToday = () => {
  33. const today = new Date();
  34. today.setHours(0, 0, 0, 0);
  35. return today;
  36. };
  37. function calcDateNum(date) {
  38. const day1 = date[0].getTime();
  39. const day2 = date[1].getTime();
  40. return (day2 - day1) / (1e3 * 60 * 60 * 24) + 1;
  41. }
  42. export {
  43. bem,
  44. calcDateNum,
  45. cloneDate,
  46. cloneDates,
  47. compareDay,
  48. compareMonth,
  49. formatMonthTitle,
  50. getDayByOffset,
  51. getNextDay,
  52. getPrevDay,
  53. getToday,
  54. name,
  55. t
  56. };