JavaScript DateTime格式化

1 篇文章 0 订阅
1 篇文章 0 订阅
        formatDate = function (date, format) {

            function stringRepeat(chr, count) {
                var str = "";
                for (var x = 0; x < count; x++) { str += chr };
                return str;
            }
            function stringPadL(s, width, pad) {
                if (!width || width < 1)
                    return s;

                if (!pad) pad = " ";
                var length = width - s.length
                if (length < 1) return s.substr(0, width);
                return (stringRepeat(pad, length) + s).substr(0, width);
            }
            function stringPadR(s, width, pad) {
                if (!width || width < 1)
                    return s;
                if (!pad) pad = " ";
                var length = width - s.length;
                if (length < 1) s.substr(0, width);
                return (s + stringRepeat(pad, length)).substr(0, width);
            }

            if (!format)
                format = "MM/dd/yyyy";
            var month = date.getMonth() + 1;
            var year = date.getFullYear();

            format = format.replace("MM", stringPadL(month.toString(), 2, "0"));

            if (format.indexOf("yyyy") > -1)
                format = format.replace("yyyy", year.toString());
            else if (format.indexOf("yy") > -1)
                format = format.replace("yy", year.toString().substr(2, 2));

            format = format.replace("dd", stringPadL(date.getDate().toString(), 2, "0"));

            var hours = date.getHours();

            if (format.indexOf("t") > -1) {
                if (hours > 11)
                    format = format.replace("t", "pm")
                else
                    format = format.replace("t", "am")
            }

            if (format.indexOf("HH") > -1)
                format = format.replace("HH", stringPadL(hours.toString(), 2, "0"));
            if (format.indexOf("hh") > -1) {
                if (hours > 12) hours - 12;
                if (hours == 0) hours = 12;
                format = format.replace("hh", stringPadL(hours.toString(), 2, "0"));
            }

            if (format.indexOf("mm") > -1)
                format = format.replace("mm", stringPadL(date.getMinutes().toString(), 2, "0"));
            if (format.indexOf("ss") > -1)
                format = format.replace("ss", stringPadL(date.getSeconds().toString(), 2, "0"));

            return format;
        };
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值