首页 > 其他分享 >js 日期格式化

js 日期格式化

时间:2023-01-04 16:01:26浏览次数:40  
标签:格式化 format fmt 日期 js length Date RegExp

1.给Date对象添加format方法,date类型的对象即可使用格式化方法(注意需要引入main.js中)

Date.prototype.format = function(fmt) {
  let 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(let 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;
};
// 使用例子
new Date().format('yyyy-MM-dd')

标签:格式化,format,fmt,日期,js,length,Date,RegExp
From: https://www.cnblogs.com/wyc-blog/p/17024982.html

相关文章