function formatDate(time,format='YY-MM-DD hh:mm:ss'){
var date = new Date(time);
var year = date.getFullYear(),
month = date.getMonth()+1,
day = date.getDate(),
hour = date.getHours(),
min = date.getMinutes(),
sec = date.getSeconds();
var preArr = Array.apply(null,Array(10)).map(function(elem, index) {
return '0'+index;
});
var newTime = format.replace(/YY/g,year)
.replace(/MM/g,preArr[month]||month)
.replace(/DD/g,preArr[day]||day)
.replace(/hh/g,preArr[hour]||hour)
.replace(/mm/g,preArr[min]||min)
.replace(/ss/g,preArr[sec]||sec);
return newTime;
}
formatDate(new Date().getTime());
formatDate(new Date().getTime(),'YY年MM月DD日');
formatDate(new Date().getTime(),'今天是YY/MM/DD hh:mm:ss');
function formatDate(date, format) {
if (!date) return;
if (!format) format = "yyyy-MM-dd";
switch (typeof date) {
case "string":
date = new Date(date.replace(/-/g, "/"));
break;
case "number":
date = new Date(date);
break;
}
if (!date instanceof Date) return;
if (date == "Invalid Date") return;
var dict = {
"yyyy": date.getFullYear(),
"M": date.getMonth() + 1,
"d": date.getDate(),
"H": date.getHours(),
"m": date.getMinutes(),
"s": date.getSeconds(),
"MM": ("" + (date.getMonth() + 101)).substr(1),
"dd": ("" + (date.getDate() + 100)).substr(1),
"HH": ("" + (date.getHours() + 100)).substr(1),
"mm": ("" + (date.getMinutes() + 100)).substr(1),
"ss": ("" + (date.getSeconds() + 100)).substr(1)
};
return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function () {
return dict[arguments[0]];
});
}
还有一种就是插件的形式,momentjs支持多种环境,在单页面应用中也是很好的
moment.js
