time_format.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. export class TimeFormatter {
  2. //格式化时间
  3. static formatTimestamp(timestamp: number): string {
  4. const currentDate = new Date();
  5. const inputDate = new Date(timestamp);
  6. // 判断是否是今天
  7. if (
  8. inputDate.getDate() === currentDate.getDate() &&
  9. inputDate.getMonth() === currentDate.getMonth() &&
  10. inputDate.getFullYear() === currentDate.getFullYear()
  11. ) {
  12. return `今天 ${TimeFormatter.formatTime(inputDate)}`;
  13. }
  14. // 判断是否是昨天
  15. const yesterday = new Date();
  16. yesterday.setDate(currentDate.getDate() - 1);
  17. if (
  18. inputDate.getDate() === yesterday.getDate() &&
  19. inputDate.getMonth() === yesterday.getMonth() &&
  20. inputDate.getFullYear() === yesterday.getFullYear()
  21. ) {
  22. return `昨天 ${TimeFormatter.formatTime(inputDate)}`;
  23. }
  24. // 判断是否是明天
  25. const tomorrow = new Date();
  26. tomorrow.setDate(currentDate.getDate() + 1);
  27. if (
  28. inputDate.getDate() === tomorrow.getDate() &&
  29. inputDate.getMonth() === tomorrow.getMonth() &&
  30. inputDate.getFullYear() === tomorrow.getFullYear()
  31. ) {
  32. return `明天 ${TimeFormatter.formatTime(inputDate)}`;
  33. }
  34. // 返回 YYYY-MM-DD HH:mm
  35. return `${inputDate.getFullYear()}-${TimeFormatter.formatNumber(inputDate.getMonth() + 1)}-${TimeFormatter.formatNumber(
  36. inputDate.getDate()
  37. )} ${TimeFormatter.formatTime(inputDate)}`;
  38. }
  39. static formatTime(date: Date): string {
  40. return `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}`;
  41. }
  42. static formatNumber(num: number): string {
  43. return num.toString().padStart(2, '0');
  44. }
  45. //计算时间间隔
  46. static calculateTimeDifference(startTimestamp: number, endTimestamp: number): string {
  47. const diff = Math.abs(endTimestamp - startTimestamp);
  48. // 计算小时、分钟和秒数
  49. const hours = Math.floor(diff / (1000 * 60 * 60));
  50. const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  51. const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  52. // 根据间隔的大小返回不同的格式
  53. if (diff < 60000) {
  54. return `${seconds}秒`;
  55. } else if (diff < 3600000) {
  56. return `${minutes}分${seconds}秒`;
  57. } else {
  58. return `${hours}小时${minutes}分${seconds}秒`;
  59. }
  60. }
  61. }