Преглед на файлове

feat: 新增金额/日期公共工具库(fenToYuan/formatMoney、parseDate/formatDuration)

skyline преди 3 седмици
родител
ревизия
eb52ab38f6
променени са 2 файла, в които са добавени 83 реда и са изтрити 0 реда
  1. 62 0
      charge-front/src/utils/date.ts
  2. 21 0
      charge-front/src/utils/money.ts

+ 62 - 0
charge-front/src/utils/date.ts

@@ -0,0 +1,62 @@
+/**
+ * 日期时间工具
+ */
+
+/**
+ * 格式化时间戳/日期为指定格式
+ * y=年 M=月 d=日 h=时 m=分 s=秒(月日时分秒不足两位补零)
+ */
+export function format(format: string, time?: number) {
+  const now = time ? new Date(time) : new Date();
+  const map: Record<string, string | number> = {
+    y: now.getFullYear(),
+    M: now.getMonth() + 1 > 9 ? now.getMonth() + 1 : `0${now.getMonth() + 1}`,
+    d: now.getDate() > 9 ? now.getDate() : `0${now.getDate()}`,
+    h: now.getHours() > 9 ? now.getHours() : `0${now.getHours()}`,
+    m: now.getMinutes() > 9 ? now.getMinutes() : `0${now.getMinutes()}`,
+    s: now.getSeconds() > 9 ? now.getSeconds() : `0${now.getSeconds()}`,
+  };
+  const res = [];
+  for (let i = 0; i < format.length; i++) {
+    if (map[format.charAt(i)]) {
+      res.push(map[format.charAt(i)]);
+    } else {
+      res.push(format.charAt(i));
+    }
+  }
+  return res.join("");
+}
+
+/**
+ * iOS 安全的日期解析:兼容 "2026-01-01 10:00:00" 格式(iOS 不支持 "-" 分隔)
+ */
+export function parseDate(str: string | number | Date): Date {
+  if (str instanceof Date) {
+    return str;
+  }
+  if (typeof str === "number") {
+    return new Date(str);
+  }
+  return new Date(String(str || "").replace(/-/g, "/"));
+}
+
+/**
+ * 充电时长格式化:"x小时y分钟" 或 "y分钟"
+ * @param minMinutes 最小时长(分钟),用于修正起止时间异常时显示 0 分钟
+ */
+export function formatDuration(start: string | number | Date, end: string | number | Date, minMinutes = 0): string {
+  const startTime = parseDate(start).getTime();
+  const endTime = parseDate(end).getTime();
+  let diff = parseInt(`${(endTime - startTime) / 1000}`);
+  if (Number.isNaN(diff) || diff < 0) {
+    diff = 0;
+  }
+  const min = parseInt(`${diff / 60}`);
+  return formatDurationMinutes(Math.max(min, minMinutes));
+}
+
+function formatDurationMinutes(min: number): string {
+  return min >= 60
+      ? `${parseInt(`${min / 60}`)}小时${parseInt(`${min - parseInt(`${min / 60}`) * 60}`)}分钟`
+      : `${min}分钟`;
+}

+ 21 - 0
charge-front/src/utils/money.ts

@@ -0,0 +1,21 @@
+/**
+ * 金额工具:后端金额统一以"分"存储
+ */
+
+/**
+ * 分转元,返回两位小数字符串(不带千分位)
+ * 无效值(undefined/null/NaN)按 0 处理
+ */
+export function fenToYuan(fen: any): string {
+  const n = Number(fen);
+  return ((Number.isFinite(n) ? n : 0) / 100).toFixed(2);
+}
+
+/**
+ * 分转元并添加千分位,用于展示,如 123456 -> "1,234.56"
+ */
+export function formatMoney(fen: any): string {
+  const [intPart, decPart] = fenToYuan(fen).split(".");
+  const withSep = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
+  return `${withSep}.${decPart}`;
+}