safety-eval-service-frontend/src/utils/dateFormat.js

80 lines
2.0 KiB
JavaScript
Raw Normal View History

2026-06-23 18:07:30 +08:00
import dayjs from "dayjs";
/** 展示2026-01-23 11:39:09 */
export function formatDateTime(value) {
if (value == null || value === "") {
return "-";
}
const d = dayjs(value);
return d.isValid() ? d.format("YYYY-MM-DD HH:mm:ss") : String(value);
}
/** 展示2026-01-23 */
export function formatDate(value) {
2026-06-26 17:28:06 +08:00
const normalized = normalizeDateValue(value);
if (normalized == null || normalized === "") {
2026-06-23 18:07:30 +08:00
return "-";
}
2026-06-26 17:28:06 +08:00
const d = dayjs(normalized);
return d.isValid() ? d.format("YYYY-MM-DD") : String(normalized);
}
/** 兼容 Jackson LocalDateTime 数组 / 对象 / 字符串 */
export function normalizeDateValue(value) {
if (value == null || value === "") {
return null;
}
if (typeof value === "string" || typeof value === "number") {
return value;
}
if (dayjs.isDayjs(value)) {
return value;
}
if (Array.isArray(value)) {
const [y, mo, d, h = 0, mi = 0, s = 0] = value;
return new Date(y, mo - 1, d, h, mi, s);
}
if (typeof value === "object") {
const y = value.year ?? value.y;
const mo = value.monthValue ?? value.month ?? value.m;
const d = value.dayOfMonth ?? value.day ?? value.d;
if (y != null && mo != null && d != null) {
return new Date(y, mo - 1, d);
}
}
return null;
2026-06-23 18:07:30 +08:00
}
/** 提交 API日期 */
export function toApiDate(value) {
if (value == null || value === "") {
return undefined;
}
if (typeof value === "string") {
return value.length > 10 ? value.slice(0, 10) : value;
}
const d = dayjs(value);
return d.isValid() ? d.format("YYYY-MM-DD") : undefined;
}
/** 提交 API日期时间 */
export function toApiDateTime(value) {
if (value == null || value === "") {
return undefined;
}
if (typeof value === "string") {
return value;
}
const d = dayjs(value);
return d.isValid() ? d.format("YYYY-MM-DDTHH:mm:ss") : undefined;
}
/** DatePicker 回显 */
export function toDayjs(value) {
if (value == null || value === "") {
return undefined;
}
const d = dayjs(value);
return d.isValid() ? d : undefined;
}