一个简单的 JavaScript 时间格式化输出工具方法函数示例:
const WEEKS = ['日', '一', '二', '三', '四', '五', '六'];
const formatFlags = {
yyyy: function(dateObj) {
return dateObj.getFullYear();
},
yy: function(dateObj) {
return String(dateObj.getFullYear()).substr(2);
},
M: function(dateObj) {
return dateObj.getMonth() + 1;
},
MM: function(dateObj) {
return pad(dateObj.getMonth() + 1);
},
d: function(dateObj) {
return dateObj.getDate();
},
dd: function(dateObj) {
return pad(dateObj.getDate());
},
H: function(dateObj) {
return dateObj.getHours();
},
HH: function(dateObj) {
return pad(dateObj.getHours());
},
h: function(dateObj) {
return dateObj.getHours() % 12 || 12;
},
hh: function(dateObj) {
return pad(dateObj.getHours() % 12 || 12);
},
m: function(dateObj) {
return dateObj.getMinutes();
},
mm: function(dateObj) {
return pad(dateObj.getMinutes());
},
s: function(dateObj) {
return dateObj.getSeconds();
},
ss: function(dateObj) {
return pad(dateObj.getSeconds());
},
w: function(dateObj) {
return WEEKS[dateObj.getDay()];
},
};
function formatDate(date, format) {
if (Object.prototype.toString.call(date).indexOf('Date') == -1) {
throw Error('Invalid date');
}
const token = /yy(?:yy)?|MM?|([dHhms])\1?|w/g;
return format.replace(token, ($0) => {
return $0 in formatFlags ? formatFlags[$0](date) : '';
});
}
function pad(str) {
str = String(str);
if (str.length < 2) {
return `0${str}`;
}
return str;
}
console.log(formatDate(new Date(), 'yyyy-M-d HH:mm:ss 星期w'));
以上就是【js 时间格式化输出工具函数】的全部内容了,欢迎留言评论进行交流!