time_format.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. export class TimeFormatter {
  2. static formatTimestamp(timestamp: number): string {
  3. const currentDate = new Date();
  4. const inputDate = new Date(timestamp);
  5. // 判断是否是今天
  6. if (
  7. inputDate.getDate() === currentDate.getDate() &&
  8. inputDate.getMonth() === currentDate.getMonth() &&
  9. inputDate.getFullYear() === currentDate.getFullYear()
  10. ) {
  11. return `今天 ${TimeFormatter.formatTime(inputDate)}`;
  12. }
  13. // 判断是否是昨天
  14. const yesterday = new Date();
  15. yesterday.setDate(currentDate.getDate() - 1);
  16. if (
  17. inputDate.getDate() === yesterday.getDate() &&
  18. inputDate.getMonth() === yesterday.getMonth() &&
  19. inputDate.getFullYear() === yesterday.getFullYear()
  20. ) {
  21. return `昨天 ${TimeFormatter.formatTime(inputDate)}`;
  22. }
  23. // 判断是否是明天
  24. const tomorrow = new Date();
  25. tomorrow.setDate(currentDate.getDate() + 1);
  26. if (
  27. inputDate.getDate() === tomorrow.getDate() &&
  28. inputDate.getMonth() === tomorrow.getMonth() &&
  29. inputDate.getFullYear() === tomorrow.getFullYear()
  30. ) {
  31. return `明天 ${TimeFormatter.formatTime(inputDate)}`;
  32. }
  33. // 返回 YYYY-MM-DD HH:mm
  34. return `${inputDate.getFullYear()}-${TimeFormatter.formatNumber(inputDate.getMonth() + 1)}-${TimeFormatter.formatNumber(
  35. inputDate.getDate()
  36. )} ${TimeFormatter.formatTime(inputDate)}`;
  37. }
  38. static formatTime(date: Date): string {
  39. return `${TimeFormatter.formatNumber(date.getHours())}:${TimeFormatter.formatNumber(date.getMinutes())}`;
  40. }
  41. static formatNumber(num: number): string {
  42. return num.toString().padStart(2, '0');
  43. }
  44. }