utils.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. export const ROW_HEIGHT = 64;
  2. export function formatMonthTitle(date) {
  3. if (!(date instanceof Date)) {
  4. date = new Date(date);
  5. }
  6. return `${date.getFullYear()}年${date.getMonth() + 1}月`;
  7. }
  8. export function compareMonth(date1, date2) {
  9. if (!(date1 instanceof Date)) {
  10. date1 = new Date(date1);
  11. }
  12. if (!(date2 instanceof Date)) {
  13. date2 = new Date(date2);
  14. }
  15. const year1 = date1.getFullYear();
  16. const year2 = date2.getFullYear();
  17. const month1 = date1.getMonth();
  18. const month2 = date2.getMonth();
  19. if (year1 === year2) {
  20. return month1 === month2 ? 0 : month1 > month2 ? 1 : -1;
  21. }
  22. return year1 > year2 ? 1 : -1;
  23. }
  24. export function compareDay(day1, day2) {
  25. if (!(day1 instanceof Date)) {
  26. day1 = new Date(day1);
  27. }
  28. if (!(day2 instanceof Date)) {
  29. day2 = new Date(day2);
  30. }
  31. const compareMonthResult = compareMonth(day1, day2);
  32. if (compareMonthResult === 0) {
  33. const date1 = day1.getDate();
  34. const date2 = day2.getDate();
  35. return date1 === date2 ? 0 : date1 > date2 ? 1 : -1;
  36. }
  37. return compareMonthResult;
  38. }
  39. export function getDayByOffset(date, offset) {
  40. date = new Date(date);
  41. date.setDate(date.getDate() + offset);
  42. return date;
  43. }
  44. export function getPrevDay(date) {
  45. return getDayByOffset(date, -1);
  46. }
  47. export function getNextDay(date) {
  48. return getDayByOffset(date, 1);
  49. }
  50. export function calcDateNum(date) {
  51. const day1 = new Date(date[0]).getTime();
  52. const day2 = new Date(date[1]).getTime();
  53. return (day2 - day1) / (1000 * 60 * 60 * 24) + 1;
  54. }
  55. export function copyDates(dates) {
  56. if (Array.isArray(dates)) {
  57. return dates.map((date) => {
  58. if (date === null) {
  59. return date;
  60. }
  61. return new Date(date);
  62. });
  63. }
  64. return new Date(dates);
  65. }
  66. export function getMonthEndDay(year, month) {
  67. return 32 - new Date(year, month - 1, 32).getDate();
  68. }
  69. export function getMonths(minDate, maxDate) {
  70. const months = [];
  71. const cursor = new Date(minDate);
  72. cursor.setDate(1);
  73. do {
  74. months.push(cursor.getTime());
  75. cursor.setMonth(cursor.getMonth() + 1);
  76. } while (compareMonth(cursor, maxDate) !== 1);
  77. return months;
  78. }