@huntianning/components
Version:
Custom components for HTN
51 lines (50 loc) • 1.18 kB
JavaScript
/**
* 格式化日期
*/
export function formatDate(date, fmt = 'YYYY-mm-dd HH:MM:SS') {
if (!date) {
return;
}
if (typeof date === 'string' || typeof date === 'number') {
date = new Date(date);
}
if (isNaN(date.getTime())) {
return;
}
let ret;
const opt = {
'Y+': date.getFullYear().toString(),
'm+': (date.getMonth() + 1).toString(),
'd+': date.getDate().toString(),
'H+': date.getHours().toString(),
'M+': date.getMinutes().toString(),
'S+': date.getSeconds().toString()
};
for (const k in opt) {
ret = new RegExp('(' + k + ')').exec(fmt);
if (ret) {
fmt = fmt.replace(ret[1], ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'));
}
}
return fmt;
}
/**
* 将时间戳或者日期字符串转为日期对象
*/
export function parseDate(date) {
if (!date) {
return;
}
if (date.getTime) {
return date;
}
if (typeof date === 'number') {
return new Date(date);
}
if (typeof date === 'string') {
const ds = date.split(/\D+/);
if (ds.length > 2) {
return new Date(ds[0], ds[1] && ds[1] - 1, ds[2], ds[3] || 0, ds[4] || 0, ds[5] || 0);
}
}
}