Javascript格式化Date日期

在做网页的时候经常要用到日期, 为了显示, 也经常要对日期对象做格式化, 下面是摘自网络(具体网址忘记了, 如果作者看到, 请留言给我, 我附上说明)的一个格式化日期的函数, 如下:

//格式化日期
Date.prototype.Format = function (fmt) {
  var o = {
    "y+": this.getFullYear(),
    "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()             //毫秒
  };
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)){
      if(k == "y+"){
        fmt = fmt.replace(RegExp.$1, ("" + o[k]).substr(4 - RegExp.$1.length));
      }
      else if(k=="S+"){
        var lens = RegExp.$1.length;
        lens = lens==1?3:lens;
        fmt = fmt.replace(RegExp.$1, ("00" + o[k]).substr(("" + o[k]).length - 1,lens));
      }
      else{
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
  }
  return fmt;
}

因为原来的格式化毫秒有问题, 所以这里我做了一点修改, 这里就不具体介绍了, 有不明白的, 可以留言给我
用法如下

var date = new Date();
console.log(date.Format("yyyy年MM月dd日 hh:mm:ss.S")); //输出: 2016年04月01日 10:41:08.133
console.log(date.Format("yyyy-MM-dd hh:mm:ss")); //输出: 2016-04-01 10:41:08
console.log(date.Format("yy-MM-dd hh:mm:ss")); //输出: 16-04-01 10:41:08
console.log(date.Format("yy-M-d hh:mm:ss")); //输出: 16-4-1 10:41:08
    原文作者:jicemoon
    原文地址: https://www.jianshu.com/p/70228e7de4b5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞