例
//输入:
formatDate(new Date(1409894060000), 'yyyy-MM-dd HH:mm:ss 星期w')
//输出:
2014-09-05 13:14:20 星期五
function formatDate(t,str){
var obj = {
yyyy:t.getFullYear(),
yy:(""+ t.getFullYear()).slice(-2),
M:t.getMonth()+1,
MM:("0"+ (t.getMonth()+1)).slice(-2),
d:t.getDate(),
dd:("0" + t.getDate()).slice(-2),
H:t.getHours(),
HH:("0" + t.getHours()).slice(-2),
h:t.getHours() % 12,
hh:("0"+t.getHours() % 12).slice(-2),
m:t.getMinutes(),
mm:("0" + t.getMinutes()).slice(-2),
s:t.getSeconds(),
ss:("0" + t.getSeconds()).slice(-2),
w:['日', '一', '二', '三', '四', '五', '六'][t.getDay()]
};
return str.replace(/([a-z]+)/ig,function($1){return obj[$1]});
}
function formatDate(date, format) {
let hours = date.getHours();
let keyMap = {
"y": date.getFullYear(),
"M": date.getMonth()+1,
"d": date.getDate(),
"H": hours,
"h": hours > 12 ? hours -12 : hours,
"m": date.getMinutes(),
"s": date.getSeconds(),
"w": date.getDay(),
};
Object.keys(keyMap).forEach((key) => {
format = format.replace(new RegExp(`${key}+`, "g"), function(s){
let value = String(keyMap[key]);
if(key === "y"){
return ("0000"+value).slice(-s.length);
}
return key === "w" ? "日一二三四五六"[value] : ("00"+value).slice(-Math.max(value.length, s.length));
})
})
return format;
}
unction formatDate(oDate, sFormation) {
var obj={
yyyy: oDate.getFullYear(),
yy: oDate.getFullYear()%100,
M: oDate.getMonth()+1,
d: oDate.getDate(),
H: oDate.getHours(),
h: oDate.getHours()%12,
m: oDate.getMinutes(),
s: oDate.getSeconds(),
w: ['日', '一', '二', '三', '四', '五', '六'][oDate.getDay()]
};
return sFormation.replace(/([a-zA-Z]+)/g,function($1){
return $1.length===2&&$1!=='yy' ? ('0'+obj[$1.slice(1)]).slice(-2) : obj[$1];
});
}