js 自定义日期(Date)格式化

来源:互联网 发布:淘宝网折800女士皮草 编辑:程序博客网 时间:2024/06/02 06:20

1.日期格式化形式如下:

Tues Apr 18 15:06:21 2016

2.格式化代码如下:


Date.prototype.Format = function(fmt) {
var o = {
“d+” : this.getDate(), //日
“h+” : this.getHours(), //小时
“m+” : this.getMinutes(), //分
“s+” : this.getSeconds(), //秒
“q+” : Math.floor((this.getMonth() + 3) / 3), //季度
“S” : this.getMilliseconds(),//毫秒
};
//(1)首先匹配字典o中的内容,否则后面周几和月份的英文也会参与该匹配
for ( var k in o)
//alert(k);
if (new RegExp(“(” + k + “)”).test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
: ((“00” + o[k]).substr((“” + o[k]).length)));

    //(2)年份       if (/(y+)/.test(fmt))        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")                .substr(4 - RegExp.$1.length));    //(3)将一周的第“N(0-6)”天用英文表达    var week = {                     "0" : "Mon",                     "1" : "Tues",                     "2" : "Wed",                     "3" : "Thur",                     "4" : "Fri",                     "5" : "Sat",                     "6" : "Sun"                    };     if(/(W+)/.test(fmt)){                 fmt=fmt.replace(RegExp.$1, week[this.getDay()+""]);             }      //(4)将月份"N(0-11)"用英文表达    var eMonth={            "0" : "Jan",                     "1" : "Feb",                     "2" : "Mar",                     "3" : "Apr",                     "4" : "May",                     "5" : "Jun",                     "6" : "Jul",                 "7" : "Aug",                         "8" : "Sept",                         "9" : "Oct",                         "10" : "Nov",                         "11" : "Dec",             }    if(/(M+)/.test(fmt)){                 fmt=fmt.replace(RegExp.$1,eMonth[this.getMonth()+""]);             }    return fmt;}

3.调用方法


var myFormat = new Date().Format("W M dd hh:mm:ss yyyy");
alert(myFormat);

0 0