常用的时间格式转换
每次时间的转换都很麻烦,所以想着封装一个时间工具函数,可以处理各种类型的时间数据
/**
格式化时间戳 / Date / 字符串
@param datetime 时间戳,单位为毫秒 / Date / string
@param format 时间格式,如YYYY-MM-DD hh:mm:ss
@returns 返回格式化后的时间字符串
*/
function formatTime(datetime: number | Date | string, format='YYYY-MM-DD hh:mm:ss'): string {
const date = new Date(datetime);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
const map: { [key: string]: string } = {
YYYY: String(year),
MM: month,
DD: day,
hh: hours,
mm: minutes,
ss: seconds,
};
return format.replace(/YYYY|MM|DD|hh|mm|ss/g, (matched) => map[matched]);
}
export default formatTime;