关于在JS中处理时间格式

假设在页面上有两个时间选择器DatePicker,我们希望用户一进来就有一个默认时间,通常我们会希望通过这样的方式
this.formatDate(new Date(new Date()-24*60*60*1000*90),"yyyy-MM-dd hh:mm:ss")

而且假设你已经加过 这样的方法:
            formatDate:function(date,formatStr){
  var newDate = new Date();
  newDate.setTime(date.getTime());
  return newDate.Format(formatStr);
},
以及这样的设置:
Date.prototype.Format = function (fmt) {
                    var o = {
                        "M+": this.getMonth() + 1, //月份
                        "d+": this.getDate(),//日
                        "h+": this.getHours(), //小时
                        "m+": this.getMinutes(), //分
                        "s+": this.getSeconds(), //秒
                        "q+": Math.floor((this.getMonth() + 3) / 3),//季度
                        "S": this.getMilliseconds() //毫秒
                        };


                        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)) {
                            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                        }
                        }
                        return fmt;
                    }
你仍然可能会得到一个错误 “vue.esm.js?65d7:1741 TypeError: newDate.Format is not a function”


如果你正好用的是Vue,那么首先还是要先了解Vue的生命周期,在我这里放在,我调用的方法放在created中,但是以上代码却放在mounted中,导致一直出现错误,就是因为Date.prototype.Format这个时候还不可用,
把上面这段代码放到Create方法中并在具体调用的方法前面,问题就解决了。

猜你喜欢

转载自blog.csdn.net/kielin/article/details/81019659