比较好用的 js 时间格式化方法,复杂的多种格式。

Date.prototype.format = function (mask) {
    var d = this;
    var zeroize = function (value, length) {
        if (!length) length = 2;
        value = String(value);
        for (var i = 0, zeros = ''; i < (length - value.length) ; i++) {
            zeros += '0';
        }
        return zeros + value;
    };

    return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0) {
        switch ($0) {
            case 'd':
                return d.getDate();
            case 'dd':
                return zeroize(d.getDate());
            case 'ddd':
                return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
            case 'dddd':
                return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
            case 'M':
                return d.getMonth() + 1;
            case 'MM':
                return zeroize(d.getMonth() + 1);
            case 'MMM':
                return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
            case 'MMMM':
                return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
            case 'yy':
                return String(d.getFullYear()).substr(2);
            case 'yyyy':
                return d.getFullYear();
            case 'h':
                return d.getHours() % 12 || 12;
            case 'hh':
                return zeroize(d.getHours() % 12 || 12);
            case 'H':
                return d.getHours();
            case 'HH':
                return zeroize(d.getHours());
            case 'm':
                return d.getMinutes();
            case 'mm':
                return zeroize(d.getMinutes());
            case 's':
                return d.getSeconds();
            case 'ss':
                return zeroize(d.getSeconds());
            case 'l':
                return zeroize(d.getMilliseconds(), 3);
            case 'L':
                var m = d.getMilliseconds();
                if (m > 99) m = Math.round(m / 10);
                return zeroize(m);
            case 'tt':
                return d.getHours() < 12 ? 'am' : 'pm';
            case 'TT':
                return d.getHours() < 12 ? 'AM' : 'PM';
            case 'Z':
                return d.toUTCString().match(/[A-Z]+$/);
                // Return quoted strings with the surrounding quotes removed
            default:
                return $0.substr(1, $0.length - 2);
        }
    });
};

实现String转bytes属性扩展

String.prototype.toBytes = function () {
var ch, st, re = [];
for (var i = 0; i < this.length; i++) {
ch = this.charCodeAt(i); // get char
st = []; // set up "stack"
do {
st.push(ch & 0xFF); // push byte to stack
ch = ch >> 8; // shift value down by 1 byte
}
while (ch);
// add stack contents to result
// done because chars have "wrong" endianness
re = re.concat(st.reverse());
}
// return an array of bytes
return re;
}

解决微软MVC请求响应的JSON的日期格式问题。需要结合StringBuilder

JavaScriptSerializer = {};
JavaScriptSerializer._charsToEscapeRegExs = [];
JavaScriptSerializer._charsToEscape = [];
JavaScriptSerializer._dateRegEx = new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)\\\\/\\"', 'g');
JavaScriptSerializer._escapeChars = {};
JavaScriptSerializer._escapeRegEx = new RegExp('["\\\\\\x00-\\x1F]', 'i');
JavaScriptSerializer._escapeRegExGlobal = new RegExp('["\\\\\\x00-\\x1F]', 'g');
JavaScriptSerializer._jsonRegEx = new RegExp('[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]', 'g');
JavaScriptSerializer._jsonStringRegEx = new RegExp('"(\\\\.|[^"\\\\])*"', 'g');
JavaScriptSerializer._init = function () {
    var replaceChars = ['\\u0000', '\\u0001', '\\u0002', '\\u0003', '\\u0004', '\\u0005', '\\u0006', '\\u0007',
                        '\\b', '\\t', '\\n', '\\u000b', '\\f', '\\r', '\\u000e', '\\u000f', '\\u0010', '\\u0011',
                        '\\u0012', '\\u0013', '\\u0014', '\\u0015', '\\u0016', '\\u0017', '\\u0018', '\\u0019',
                        '\\u001a', '\\u001b', '\\u001c', '\\u001d', '\\u001e', '\\u001f'];
    JavaScriptSerializer._charsToEscape[0] = '\\';
    JavaScriptSerializer._charsToEscapeRegExs['\\'] = new RegExp('\\\\', 'g');
    JavaScriptSerializer._escapeChars['\\'] = '\\\\';
    JavaScriptSerializer._charsToEscape[1] = '"';
    JavaScriptSerializer._charsToEscapeRegExs['"'] = new RegExp('"', 'g');
    JavaScriptSerializer._escapeChars['"'] = '\\"';
    for (var i = 0; i < 32; i++) {
        var c = String.fromCharCode(i);
        JavaScriptSerializer._charsToEscape[i + 2] = c;
        JavaScriptSerializer._charsToEscapeRegExs[c] = new RegExp(c, 'g');
        JavaScriptSerializer._escapeChars[c] = replaceChars[i];
    }
}
JavaScriptSerializer.serialize = function (object) {
    var stringBuilder = new StringBuilder();
    var booleanWithBuilder = function (bool, builder) {
        if (typeof bool !== 'undefined') {
            builder.append(bool);
        } else {
            builder.append('false');
        }
    }
    var numberWithBuilder = function (number, builder) {
        if (typeof number !== 'undefined' && number.toString() !== 'NaN') {
            builder.append(number);
        } else {
            builder.append('null');
        }
    }
    var stringWithBuilder = function (string, builder) {
        builder.append('"');
        if (JavaScriptSerializer._escapeRegEx.test(string)) {
            if (JavaScriptSerializer._charsToEscape.length === 0) {
                JavaScriptSerializer._init();
            }
            if (string.length < 128) {
                string = string.replace(JavaScriptSerializer._escapeRegExGlobal,
                function (x) { return JavaScriptSerializer._escapeChars[x]; });
            }
            else {
                for (var i = 0; i < 34; i++) {
                    var c = JavaScriptSerializer._charsToEscape[i];
                    if (string.indexOf(c) !== -1) {
                        if ($.browser.opera || $.browser.mozilla) {
                            string = string.split(c).join(JavaScriptSerializer._escapeChars[c]);
                        }
                        else {
                            string = string.replace(JavaScriptSerializer._charsToEscapeRegExs[c],
                            JavaScriptSerializer._escapeChars[c]);
                        }
                    }
                }
            }
        }
        builder.append(string);
        builder.append('"');
    }
    var dateWithBuilder = function (date, builder) {
        if (date && date.toString() !== 'NaN') {
            builder.append('"\\/Date(');
            var timeOffset = date.getTimezoneOffset() * 60 * 1000;
            if (timeOffset != 0) {
                var time = date.getTime() - timeOffset;
                builder.append(time);
            }
            else {
                builder.append(date.getTime());
            }
            builder.append(')\\/"');
        } else {
            builder.append('null');
        }
    }
    var plainObjectWithBuilder = function (plainObject, builder) {
        builder.append('{');
        var row = 0;
        for (var item in plainObject) {
            if (row++ > 0) {
                builder.append(',');
            }
            stringWithBuilder(item, builder);
            builder.append(':');
            withBuilder(plainObject[item], builder);
        }
        builder.append('}');
    }
    var arrayWithBuilder = function (array, builder) {
        if (array) {
            builder.append('[');
            if (array.length > 0) {
                $.each(array, function (i, item) {
                    if (i > 0) {
                        builder.append(',');
                    }
                    withBuilder(item, builder);
                });
            }
            builder.append(']');
        } else {
            builder.append('null');
        }
    }
    var withBuilder = function (object, builder) {
        builder = builder || new StringBuilder();
        var type = $.type(object);
        switch (type) {
            case 'object':
                if (object) {
                    if (jQuery.isPlainObject(object)) {
                        plainObjectWithBuilder(object, builder);
                    } else {
                        builder.append('null');
                    }
                } else {
                    builder.append('null');
                }
                break;
            case 'array':
                arrayWithBuilder(object, builder);
                break;
            case 'number':
                numberWithBuilder(object, builder);
                break;
            case 'string':
                stringWithBuilder(object, builder);
                break;
            case 'date':
                dateWithBuilder(object, builder);
                break;
            case 'boolean':
                booleanWithBuilder(object, builder);
                break;
            default:
                builder.append('null');
                break;
        }
    }

    withBuilder(object, stringBuilder);

    return stringBuilder.toString();
}
JavaScriptSerializer.deserialize = function (data, secure) {
    if (data == null || typeof data !== "string" || data.length === 0) {
        return null;
    }
    var exp = data.replace(JavaScriptSerializer._dateRegEx, "$1new Date($2)");
    try {
        if (secure && JavaScriptSerializer._jsonRegEx.test(exp.replace(JavaScriptSerializer._jsonStringRegEx, ''))) {
            throw null;
        }
    } catch (e) {
        throw 'Cannot deserialize. The data does not correspond to valid JSON.';
    }
    return eval('(' + exp + ')');
}

StringBuilder = function (initialText) {
    this._array = (typeof (initialText) !== 'undefined' && initialText !== null && initialText !== '') ? [initialText] : [];
    this.append = function (text) {
        this._array[this._array.length] = text;
    }
    this.appendLine = function (text) {
        this._array[this._array.length] = ((typeof (text) === 'undefined') || (text === null) || (text === '')) ? '\r\n' : text + '\r\n';
    }
    this.clear = function (text) {
        this._array = [];
    }
    this.isEmpty = function () {
        return (this._array.length == 0 ? true : false);
    }
    this.toString = function (separator) {
        separator = separator || ''
        var array = this._array;
        if (separator !== '') {
            for (var i = 0; i < array.length; ) {
                if ((typeof (array[i]) === 'undefined') || (array[i] === '') || (array[i] === null)) {
                    array.splice(i, 1);
                }
                else {
                    i++;
                }
            }
        }
        return array.join(separator);
    }
    this.indexOf = function (searchvalue) {
        return this._array.indexOf(searchvalue);
    }
    this.contains = function (text) {
        return this._array.contains(text);
    }
}