date.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * 日期时间工具
  3. */
  4. /**
  5. * 格式化时间戳/日期为指定格式
  6. * y=年 M=月 d=日 h=时 m=分 s=秒(月日时分秒不足两位补零)
  7. */
  8. export function format(format: string, time?: number) {
  9. const now = time ? new Date(time) : new Date();
  10. const map: Record<string, string | number> = {
  11. y: now.getFullYear(),
  12. M: now.getMonth() + 1 > 9 ? now.getMonth() + 1 : `0${now.getMonth() + 1}`,
  13. d: now.getDate() > 9 ? now.getDate() : `0${now.getDate()}`,
  14. h: now.getHours() > 9 ? now.getHours() : `0${now.getHours()}`,
  15. m: now.getMinutes() > 9 ? now.getMinutes() : `0${now.getMinutes()}`,
  16. s: now.getSeconds() > 9 ? now.getSeconds() : `0${now.getSeconds()}`,
  17. };
  18. const res = [];
  19. for (let i = 0; i < format.length; i++) {
  20. if (map[format.charAt(i)]) {
  21. res.push(map[format.charAt(i)]);
  22. } else {
  23. res.push(format.charAt(i));
  24. }
  25. }
  26. return res.join("");
  27. }
  28. /**
  29. * iOS 安全的日期解析:兼容 "2026-01-01 10:00:00" 格式(iOS 不支持 "-" 分隔)
  30. */
  31. export function parseDate(str: string | number | Date): Date {
  32. if (str instanceof Date) {
  33. return str;
  34. }
  35. if (typeof str === "number") {
  36. return new Date(str);
  37. }
  38. return new Date(String(str || "").replace(/-/g, "/"));
  39. }
  40. /**
  41. * 充电时长格式化:"x小时y分钟" 或 "y分钟"
  42. * @param minMinutes 最小时长(分钟),用于修正起止时间异常时显示 0 分钟
  43. */
  44. export function formatDuration(start: string | number | Date, end: string | number | Date, minMinutes = 0): string {
  45. const startTime = parseDate(start).getTime();
  46. const endTime = parseDate(end).getTime();
  47. let diff = parseInt(`${(endTime - startTime) / 1000}`);
  48. if (Number.isNaN(diff) || diff < 0) {
  49. diff = 0;
  50. }
  51. const min = parseInt(`${diff / 60}`);
  52. return formatDurationMinutes(Math.max(min, minMinutes));
  53. }
  54. function formatDurationMinutes(min: number): string {
  55. return min >= 60
  56. ? `${parseInt(`${min / 60}`)}小时${parseInt(`${min - parseInt(`${min / 60}`) * 60}`)}分钟`
  57. : `${min}分钟`;
  58. }