时间日期格式化封装dateFormat

365 阅读1分钟

前言

   俗话说“好记性不如烂笔头”,此文仅用于记录自我知识库

一、dateFormat,时间日期格式化封装函数

   为了方便项目需求的各种时间日期格式展示转换,对该功能做的一个封装

二、实现代码

/***
 * @param time 13位时间戳 || date字符串(能转化成new Date的数据均可)
 * @param fmt 转化格式
 * @returns {string} 转换后的字符串
 */
function dateFormat(time, fmt = "yyyy-MM-dd hh:mm:ss") {
  if (!time) {
    return "";
  }
  const date = new Date(time);
  const o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").slice(4 - RegExp.$1.length)
    );
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        str.padStart(RegExp.$1.length,"0")
      );
    }
  }
  return fmt;
}

/* 栗子 */
dateFormat(new Date());
// '2022-10-21 13:19:29'
dateFormat(new Date(), "yyyy-MM-dd");
// '2022-10-21'
dateFormat("2022-10-21", "yyyy年MM月dd日 hh时mm分ss秒");
// '2022年10月21日 13时19分29秒'
dateFormat("2021-06-05 08:29:05", "yy-M-d h:m:s");
// '21-6-5 8:29:5'