您的位置:首页 > Web前端 > JavaScript

javascript Date format(js日期格式化)

2017-11-30 16:41 399 查看
对Date的扩展,将 Date 转化为指定格式的String

// 月(M)、日(d)、12小时(H)、24小时(h)、分(m)、秒(s)、周(E)、季度(q)可以用 1-2 个占位符
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// (new Date()).format("yyyy-MM-dd HH:mm:ss.S")==> 2017-07-02 08:09:04.423
// (new Date()).format("yyyy年MM月dd日 E hh:mm:ss") ==> 2017年03月10日 二 20:09:04
// (new Date()).format("yyyy-MM-dd EE hh:mm:ss") ==> 2017-03-10 周二 20:09:04
// (new Date()).format("yyyy-MM-dd EEE hh:mm:ss") ==> 2017-03-10 星期二 20:09:04
// (new Date()).format("yyyy-M-d h:m:s.S") ==> 2017-7-2 8:9:4.18
<script language="javascript" type="text/javascript">
Date.prototype.format=function(format) {
var date = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"H+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //12小时制(需要加上上午下午)
"h+" : this.getHours(), //24小时制
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
var week = {
"0" : "日",
"1" : "一",
"2" : "二",
"3" : "三",
"4" : "四",
"5" : "五",
"6" : "六"
};
//年(y)可以选择用 1-4 个占位符(如:17,2017)
if(/(y+)/.test(format)){
format=format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
//周(E)可以选择用 1-3 个占位符(如:一,周一,星期一)
if(/(E+)/.test(format)){
format=format.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "星期" : "周") : "")+week[this.getDay()+""]);
}
//date中的其他月/日/小时/分钟/秒等可以选择用 1-2 个占位符(如:7,07)
for(var i in date){
if(new RegExp("("+ i +")").test(format)){
format = format.replace(RegExp.$1, (RegExp.$1.length==1) ? (date[i]) : (("00"+ date[i]).substr((""+ date[i]).length)));
}
}
return format;
};

调用:
var time1 = new Date().format("yyyy-MM-dd EE hh:mm:ss");
var time2 = new Date().format("yyyy-MM-dd EEE hh:mm:ss");
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: