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

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

4.方式2
export function formatDate(date, str) {
  date = new Date(date);
  str = str ? str : "yyyy/MM/dd hh:mm:ss";
  if (/(y+)/.test(str)) {
   str = str.replace(RegExp.$1, String(date.getFullYear()).substr(4 - RegExp.$1.length));
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(str)) {
      let stry = String(o[k]);
      str = str.replace(RegExp.$1, RegExp.$1.length === 1 ? stry : ("00" + stry).substr(stry.length));
    }
  }
  return str;
}
const t = formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
console.log("t", t); // 2022/10/31 18:52:25
posted @ 2022-09-07 10:13  SKa-M  阅读(1193)  评论(0编辑  收藏  举报