美文网首页
js时间对象的格式化

js时间对象的格式化

作者: 小呆糊总 | 来源:发表于2019-03-20 15:52 被阅读0次
    var myDate = new Date();//返回:Wed Mar 20 2019 15:15:11 GMT+0800 (中国标准时间)
    var mytime=myDate.format('yyyy-MM-dd');//返回:2019-03-20
    
    /*如果是一个后台获取的下拉框,每个下拉框包含数据startData是一个
    时间戳,把时间戳转化成2019-03-20格式*/
    <select name="food" >
        <option value="pingguo" index="0">苹果</option>
        <option value="li" index="1">梨</option>
        <option value="tao" index="2">桃子</option>
        <option value="you" index="3">柚子</option>
    </select>
    //后台接口返回的json
    {
      "status" : true,
      "message" : null,
      "data" : [ {
        "id" : 6,
        "name" : "苹果",
        "startDate" : 1552579200000,
      }, {
        "id" : 6,
        "name" : "梨",
        "startDate" : 1552579300000,
      }, {
        "id" : 6,
        "name" : "桃子",
        "startDate" : 1552578200000,
      }, {
        "id" : 6,
        "name" : "柚子",
        "startDate" : 1552579800000,
      }]
    }
    //下拉列表属性index为接口返回的数据data[i]的i值
    var index=$(this).find("option:selected").attr('index');//1552579200000
    var myDate = new Date(response.data[index].startDate);
    var payDate=myDate.format('yyyy-MM-dd');//2019-03-20
    
     // 时间对象的格式化; 
    Date.prototype.format = function (format) {
        /* 
         * eg:format="yyyy-MM-dd hh:mm:ss"; 
         */
        var o = {
            "M+": this.getMonth() + 1, // month  
            "d+": this.getDate(), // day  
            "h+": this.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(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }
    

    相关文章

      网友评论

          本文标题:js时间对象的格式化

          本文链接:https://www.haomeiwen.com/subject/okazmqtx.html