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

80 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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) {
const normalized = normalizeDateValue(value);
if (normalized == null || normalized === "") {
return "-";
}
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;
}
/** 提交 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;
}