A8000
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.5 KiB

8 months ago
  1. // dateUtils.ts
  2. /**
  3. *
  4. * @param timestamp - Date对象
  5. * @param format - 'YYYY-MM-DD HH:mm:ss'
  6. * @returns
  7. */
  8. export function formatDate(
  9. timestamp: number | string | Date,
  10. format: string = 'YYYY-MM-DD HH:mm:ss'
  11. ): string {
  12. if (!timestamp) return '';
  13. let date: Date;
  14. // 处理不同类型的输入
  15. if (timestamp instanceof Date) {
  16. date = timestamp;
  17. } else {
  18. let tsNumber = Number(timestamp);
  19. if (isNaN(tsNumber)) {
  20. console.error('Invalid timestamp:', timestamp);
  21. return '';
  22. }
  23. // 判断时间戳是秒还是毫秒级别
  24. if (String(Math.floor(tsNumber)).length === 10) {
  25. tsNumber *= 1000; // 秒级时间戳转毫秒
  26. }
  27. date = new Date(tsNumber);
  28. }
  29. if (isNaN(date.getTime())) {
  30. console.error('Invalid date:', date);
  31. return '';
  32. }
  33. const map: { [key in 'YYYY' | 'MM' | 'DD' | 'HH' | 'mm' | 'ss']: string } = {
  34. YYYY: date.getFullYear().toString(),
  35. MM: ('0' + (date.getMonth() + 1)).slice(-2),
  36. DD: ('0' + date.getDate()).slice(-2),
  37. HH: ('0' + date.getHours()).slice(-2),
  38. mm: ('0' + date.getMinutes()).slice(-2),
  39. ss: ('0' + date.getSeconds()).slice(-2),
  40. };
  41. // 使用正则替换格式字符串中的标记
  42. const formattedDate = format.replace(/YYYY|MM|DD|HH|mm|ss/g, (pattern) => {
  43. return map[pattern as keyof typeof map];
  44. });
  45. return formattedDate;
  46. }