zoukankan      html  css  js  c++  java
  • 一个格式化日期和时间的JavaScript类库

      原文地址:http://www.cnblogs.com/zhangpengshou/archive/2012/07/19/2599053.html

      结合meizz的代码做了适当调整。

    Date.prototype.Format = function (fmt) {
        var that = this;
        var postfix = false;
        var o = {
            "M+": this.getMonth() + 1, //month
            "d+": this.getDate(), //day
            "h+": function () {
                return postfix ? (that.getHours() % 12 == 0 ? 12 : that.getHours() % 12) : that.getHours();
            }, //hour
            "m+": this.getMinutes(), //minute
            "s+": this.getSeconds(), //second
            "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
            "S": this.getMilliseconds() //millisecond
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                if (RegExp.$1.length == 1 && RegExp.$1 == "h") postfix = true;
                var val = typeof (o[k]) == "function" ? o[k].apply(this) : o[k];
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (val) : (("00" + val).substr(("" + val).length)));
                
            }
        }
        return fmt + (postfix ? ((this.getHours() < 12) ? " AM" : " PM") : "");
    }
    
    // following are testing code
    var Ld = "26-09-2014"; var Lt = "13:15:23"; var arrDateParts = Ld.split("-"); if (arrDateParts.length == 3) { var dayNum = arrDateParts[0]; var monthNum = arrDateParts[1]; var yearNum = arrDateParts[2]; var D = new Date(monthNum.concat("/", dayNum, "/", yearNum, ' ', Lt)); console.info(D.Format("M/dd/yyyy h:mm:ss")); }

      以上代码可根据所提供的格式字符串以及时间来判断是否需要添加AM/PM后缀。

  • 相关阅读:
    JAVA中toString方法
    编辑器未包含main类型解决方法
    Ubuntu中设置环境变量详解
    vim中执行shell命令小结
    vim使用手册
    vim命令总结
    如何修改远程桌面连接3389端口
    Linux磁盘与文件系统管理
    文件与文件系统的压缩与打包命令
    Mininet VM设置笔记
  • 原文地址:https://www.cnblogs.com/jaxu/p/3998736.html
Copyright © 2011-2022 走看看