import dayjs from 'dayjs'; /** * 计算两个日期之间经过的时间,如 "3分12秒" * * @param {string | null | undefined} begin - The starting date. * @param {string | null | undefined} end - The ending date. * @return {string} The formatted elapsed time string. */ export const elapsedTime = (begin?: string | null, end?: string | null): string => { if (begin === undefined || begin === null) { return '--'; } const beginDate = dayjs(begin); const endDate = end === undefined || end === null ? dayjs() : dayjs(end); if (!beginDate.isValid() || !endDate.isValid()) { return '--'; } const timestamp = endDate.valueOf() - beginDate.valueOf(); if (timestamp < 0) { return '0秒'; } const duration = dayjs.duration(timestamp); const years = duration.years(); const months = duration.months(); const days = duration.days(); const hours = duration.hours(); const minutes = duration.minutes(); const seconds = duration.seconds(); const elspsedArray = []; if (years !== 0) { elspsedArray.push(`${years}年`); } if (months !== 0) { elspsedArray.push(`${months}个月`); } if (days !== 0) { elspsedArray.push(`${days}天`); } if (hours !== 0) { elspsedArray.push(`${hours}小时`); } if (minutes !== 0) { elspsedArray.push(`${minutes}分`); } if (seconds !== 0) { elspsedArray.push(`${seconds}秒`); } if (elspsedArray.length === 0) { return '0秒'; } return elspsedArray.slice(0, 2).join(''); }; /** * 是否是有效的日期 * * @param {Date} date - The date to check. * @return {boolean} True if the date is valid, false otherwise. */ export const isValidDate = (date: Date): boolean => { if (date instanceof Date) { return !Number.isNaN(date.getTime()); // valueOf() 也可以 } return false; }; /** * 能否使用 dayjs 转换成 Date * * @param {Date | string | number | null | undefined} date - The date to be checked. * @return {boolean} Returns true if the date can be converted to a valid Date object, otherwise returns false. */ export const canBeConvertToDate = (date?: Date | string | number | null): boolean => { if (date === undefined || date === null || date === '') { return false; } const convertedDate = dayjs(date); return convertedDate.isValid(); }; /** * 转换日期 * * @param {Date | string | number | null | undefined} date - The date to format. * @param {string} [format='YYYY-MM-DD HH:mm:ss'] - The format string to use. * @return {string} The formatted date string. */ export const formatDate = ( date: Date | string | number | null | undefined, format: string = 'YYYY-MM-DD HH:mm:ss', ): string => { if (date === undefined || date === null || date === '') { return '--'; } const convertedDate = dayjs(date); if (!convertedDate.isValid()) { return '--'; } return convertedDate.format(format); };