utils.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 getToday() {
  51. const today = new Date();
  52. today.setHours(0, 0, 0, 0);
  53. return today;
  54. }
  55. export function calcDateNum(date) {
  56. const day1 = new Date(date[0]).getTime();
  57. const day2 = new Date(date[1]).getTime();
  58. return (day2 - day1) / (1000 * 60 * 60 * 24) + 1;
  59. }
  60. export function copyDates(dates) {
  61. if (Array.isArray(dates)) {
  62. return dates.map((date) => {
  63. if (date === null) {
  64. return date;
  65. }
  66. return new Date(date);
  67. });
  68. }
  69. return new Date(dates);
  70. }
  71. export function getMonthEndDay(year, month) {
  72. return 32 - new Date(year, month - 1, 32).getDate();
  73. }
  74. export function getMonths(minDate, maxDate) {
  75. const months = [];
  76. const cursor = new Date(minDate);
  77. cursor.setDate(1);
  78. do {
  79. months.push(cursor.getTime());
  80. cursor.setMonth(cursor.getMonth() + 1);
  81. } while (compareMonth(cursor, maxDate) !== 1);
  82. return months;
  83. }