Date 增加格式化功能

1 篇文章 / 0 new
author
Date 增加格式化功能
//月份
var gsMonthNames = new Array( '一','二','三','四','五','六','七','八','九','十','十一','十二');
//星期
var gsDayNames = new Array( '一','二','三','四','五','六','日');
//擴充Date方法
Date.prototype.formatDateTime = function(f)
{
    if (!this.valueOf())
        return ' ';
 
    var d = this;
 
    return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
        function($1)
        {
            switch ($1.toLowerCase())
            {
            case 'yyyy': return d.getFullYear();
            case 'mmmm': return gsMonthNames[d.getMonth()];
            case 'mmm':  return gsMonthNames[d.getMonth()].substr(0, 3);
            case 'mm':   return (d.getMonth() + 1).zf(2);
            case 'dddd': return gsDayNames[d.getDay()];
            case 'ddd':  return gsDayNames[d.getDay()].substr(0, 3);
            case 'dd':   return d.getDate().zf(2);
            case 'hh':   return ((h = d.getHours() % 12) ? h : 12).zf(2);
            case 'nn':   return d.getMinutes().zf(2);
            case 'ss':   return d.getSeconds().zf(2);
            case 'a/p':  return d.getHours() < 12 ? 'a' : 'p';
            }
        }
    );
}
//補足位數
String.prototype.zf = function (width, pad) {
    var length = this.length;
    if (!width || width <= length)
        return this;
    if (!pad) pad = "0";
    var d = this;
    while (width > length) {
        d = pad + d;
        length = length+1;
    }
    return d;
}
Free Web Hosting