js 日期格式化
1.代码实现
/**
* 对Date类型进行格式化(转化为指定格式的String)
* @explain 年(y)可以用 1-4 个占位符
* 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、季度(q) 都可以用 1-2 个占位符
* 周(E)可以用 1-3 个占位符
* 毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
* @param fmt 格式
* 常用格式介绍:
* yyyy年MM月dd日 2018年08月29日
* yyyy-MM-dd HH:mm:ss 2018-08-29 14:17:15
* yyyy-MM-dd hh:mm:ss S 2018-08-29 14:17:15 10
* yyyy-MM-dd EE HH:mm:ss 2018-08-29 周三 14:17:15
* yyyy-MM-dd EEE HH:mm:ss 2018-08-29 星期三
*/
Date.prototype.format = function (fmt) {
var o = {
"M+" : this .getMonth() + 1, // 月份
"d+" : this .getDate(), // 日
"h+" : this .getHours() % 12 == 0 ? 12 : this .getHours() % 12, // 小时
"H+" : this .getHours(), // 小时
"m+" : this .getMinutes(), // 分
"s+" : this .getSeconds(), // 秒
"q+" : Math.floor(( this .getMonth() + 3) / 3), // 季度
"S" : this .getMilliseconds() // 毫秒
};
var week = {
"0" : "\u65e5" , // 日
"1" : "\u4e00" , // 一
"2" : "\u4e8c" , // 二
"3" : "\u4e09" , // 三
"4" : "\u56db" , // 四
"5" : "\u4e94" , // 五
"6" : "\u516d" // 六
};
// 年
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, ( this .getFullYear() + "" ).substr(4 - RegExp.$1.length));
};
// \u661f\u671f-星期;\u5468-周
if (/(E+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468" ) : "" ) + week[ this .getDay() + "" ]);
}
for ( var k in o) {
if ( new RegExp( "(" + k + ")" ).test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (( "00" + o[k]).substr(( "" + o[k]).length)));
}
}
return fmt;
};
2.测试
window.onload = function (){
document.write( new Date().format( 'yyyy年MM月dd日' ) + "
" );
document.write( new Date().format( 'yyyy-MM-01' ) + "
" );
document.write( new Date().format( 'yyyy-MM-dd HH:mm:ss' ) + "
" );
document.write( new Date().format( 'yyyy-MM-dd HH:mm:ss S' ) + "
" );
document.write( new Date().format( 'yyyy-MM-dd EE HH:mm:ss' ) + "
" );
document.write( new Date().format( 'yyyy-MM-dd EEE HH:mm:ss' ) + "
" );
document.write( new Date().format( 'yyyy-MM-dd 第qq季度 HH:mm:ss' ) + "
" );
}
3.结果展示

写在最后
哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!
相关推荐:
本文来自博客园,作者:Marydon,转载请注明原文链接:https://www.cnblogs.com/Marydon20170307/p/9554203.html
浙公网安备 33010602011771号