format-datetime
Version:
36 lines (34 loc) • 1.25 kB
JavaScript
function formatDate(dateObj,format) {
var o = {
"M+": dateObj.getMonth() + 1, //月份
"d+": dateObj.getDate(), //日
"h+": dateObj.getHours() % 12 == 0 ? 12 : dateObj.getHours() % 12, //小时
"H+": dateObj.getHours(), //小时
"m+": dateObj.getMinutes(), //分
"s+": dateObj.getSeconds(), //秒
"q+": Math.floor((dateObj.getMonth() + 3) / 3), //季度
"S": dateObj.getMilliseconds() //毫秒
};
var week = {
"0": "\u65e5",
"1": "\u4e00",
"2": "\u4e8c",
"3": "\u4e09",
"4": "\u56db",
"5": "\u4e94",
"6": "\u516d"
};
if(/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (dateObj.getFullYear() + "").substr(4 - RegExp.$1.length));
}
if(/(E+)/.test(format)) {
format = format.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[dateObj.getDay() + ""]);
}
for(var k in o) {
if(new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return format;
};
module.exports = formatDate;