首页 > 其他分享 >js实现当前时间年-月-日 时-分-秒

js实现当前时间年-月-日 时-分-秒

时间:2022-09-07 10:24:23浏览次数:81  
标签:Format 实现 fmt js yyyy 当前 RegExp Date new

1.对Date的扩展,将 Date 转化为指定格式的String

1.(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
2.(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
3.如下所示:

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;
};

4.使用例子
// 1.不加中文
const t = new Date().Format("yyyy-MM-dd hh-mm-ss");
console.log("不加中文", t);	//不加中文 2022-09-07 10-14-15

// 2.加中文
const t2 = new Date().Format("yyyy年MM月dd日 hh时mm分ss秒");
console.log("加中文", t2);	//加中文 2022年09月07日 10时14分15秒

//3.只显示年月日
const t3 = new Date().Format("yyyy-MM-dd");
console.log("只显示年月日", t3);	//只显示年月日 2022-09-07

//4.只显示时分秒
const t4 = new Date().Format("hh-mm-ss");
console.log("只显示时分秒", t4);	//只显示时分秒 10-14-15

标签:Format,实现,fmt,js,yyyy,当前,RegExp,Date,new
From: https://www.cnblogs.com/songkomei/p/16664339.html

相关文章