@ryanuo/utils
Version:
提供多种实用工具函数,涵盖算法、浏览器操作、网络请求等多个领域
54 lines (53 loc) • 1.46 kB
JavaScript
import date from "dayjs";
import { isDate, isFunction } from "./is.mjs";
export function dateFormat(date2, fmt = "YYYY-MM-dd") {
if (!isDate(date2))
throw new TypeError("Parameter must be a valid Date.");
const year = date2.getFullYear().toString();
const padLengths = {
Y: 4,
y: 2,
M: 2,
d: 2,
H: 2,
h: 2,
m: 2,
s: 2,
S: 3,
q: 1
};
const opt = {
"Y+": () => year,
"y+": (matched) => year.slice(-matched.length),
"M+": (date2.getMonth() + 1).toString(),
"d+": date2.getDate().toString(),
"H+": date2.getHours().toString(),
"h+": () => {
const hour = date2.getHours();
return (hour % 12 || 12).toString();
},
"m+": date2.getMinutes().toString(),
"s+": date2.getSeconds().toString(),
"q+": Math.floor((date2.getMonth() + 3) / 3).toString(),
"S+": date2.getMilliseconds().toString()
};
let matchRes;
for (const k in opt) {
matchRes = fmt.match(new RegExp(k, "g"));
matchRes?.forEach((matchedItem) => {
const placeholder = k.charAt(0);
const padLength = padLengths[placeholder] || matchedItem.length;
const value = opt[k];
const replacement = isFunction(opt[k]) ? value(matchedItem) : value;
fmt = fmt.replace(
matchedItem,
replacement.toString().padStart(
Math.max(matchedItem.length, padLength),
"0"
)
);
});
}
return fmt;
}
export const dayjs = date;