date.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. export const getDateRect = (date) => {
  2. const _date = new Date(date);
  3. return {
  4. year: _date.getFullYear(),
  5. month: _date.getMonth(),
  6. date: _date.getDate(),
  7. day: _date.getDay(),
  8. time: _date.getTime(),
  9. };
  10. };
  11. export const isSameDate = (date1, date2) => {
  12. if (date1 instanceof Date || typeof date1 === 'number')
  13. date1 = getDateRect(date1);
  14. if (date2 instanceof Date || typeof date2 === 'number')
  15. date2 = getDateRect(date2);
  16. const keys = ['year', 'month', 'date'];
  17. return keys.every((key) => date1[key] === date2[key]);
  18. };
  19. export const getMonthDateRect = (date) => {
  20. const { year, month } = getDateRect(date);
  21. const firstDay = new Date(year, month, 1);
  22. const weekdayOfFirstDay = firstDay.getDay();
  23. const lastDate = new Date(+new Date(year, month + 1, 1) - 24 * 3600 * 1000).getDate();
  24. return {
  25. year,
  26. month,
  27. weekdayOfFirstDay,
  28. lastDate,
  29. };
  30. };
  31. export const isValidDate = (val) => typeof val === 'number' || val instanceof Date;
  32. export const getDate = (...args) => {
  33. const now = new Date();
  34. if (args.length === 0)
  35. return now;
  36. if (args.length === 1 && args[0] <= 1000) {
  37. const { year, month, date } = getDateRect(now);
  38. return new Date(year, month + args[0], date);
  39. }
  40. return Date.apply(null, args);
  41. };