基于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;
}
本文介绍了一种使用JavaScript的Date对象进行日期格式化的实用方法,通过一个可复用的函数,能够将时间戳或日期对象转换为指定格式的日期字符串,如2018-4-13。该函数支持多种格式化样式,如年、月、日、时、分、秒及星期几。
407

被折叠的 条评论
为什么被折叠?



