基于js的Date对象,进行一些js的字符串等基本操作,返回想要的日期格式,下面是代码,直接调用就是了——
/**
* 格式化时间戳
* @param { Number | Date } time 目标时间戳/时间对象
* @param { String } cFormat 格式化样式 ({y}-{m}-{d} -> 2018-4-13)
* @retrun { String } time_str
*/
export default function formatDate(time, cFormat) {
if (!time) {
return;
}
if (arguments.length === 0) {
return null;
}
const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
let date;
if (typeof time === "object") {
date = time;
} else if (typeof time === "string") {
time = time.replace(/[-,年,月,日]/g, "/");
date = new Date(time);
} else {
if (typeof time === "number") {
if ((time + "").length === 10) {
time = +time * 1000;
}
date = new Date(parseInt(time));
} else {
date = new Date(time);
}
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
};
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key];
if (key === "a") return ["日", "一", "二", "三", "四", "五", "六"][value];
if (result.length > 0 && value < 10) {
value = "0" + value;
}
return value || 0;
});
return time_str;
}