time.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * 日期时间处理工具函数
  3. */
  4. // 格式化日期
  5. export function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  6. const d = date ? new Date(date) : new Date();
  7. const year = d.getFullYear();
  8. const month = String(d.getMonth() + 1).padStart(2, '0');
  9. const day = String(d.getDate()).padStart(2, '0');
  10. const hours = String(d.getHours()).padStart(2, '0');
  11. const minutes = String(d.getMinutes()).padStart(2, '0');
  12. const seconds = String(d.getSeconds()).padStart(2, '0');
  13. return format
  14. .replace('YYYY', year)
  15. .replace('MM', month)
  16. .replace('DD', day)
  17. .replace('HH', hours)
  18. .replace('mm', minutes)
  19. .replace('ss', seconds);
  20. }
  21. // 获取当前时间戳
  22. export function getCurrentTimestamp() {
  23. return Date.now();
  24. }
  25. // 获取指定日期的开始时间
  26. export function getStartOfDay(date) {
  27. const d = new Date(date);
  28. d.setHours(0, 0, 0, 0);
  29. return d;
  30. }
  31. // 获取指定日期的结束时间
  32. export function getEndOfDay(date) {
  33. const d = new Date(date);
  34. d.setHours(23, 59, 59, 999);
  35. return d;
  36. }
  37. // 计算两个日期之间的天数差
  38. export function getDaysDiff(date1, date2) {
  39. const d1 = new Date(date1);
  40. const d2 = new Date(date2);
  41. const diffTime = Math.abs(d2 - d1);
  42. return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  43. }
  44. // 判断是否为同一天
  45. export function isSameDay(date1, date2) {
  46. const d1 = new Date(date1);
  47. const d2 = new Date(date2);
  48. return (
  49. d1.getFullYear() === d2.getFullYear() &&
  50. d1.getMonth() === d2.getMonth() &&
  51. d1.getDate() === d2.getDate()
  52. );
  53. }