JS格式化时间为各种常用字符串类型

可以将Date转为项目中常用到的各种string类型

// 项目中使用到了ts,不需要请手动删除掉ts相关代码
function formatDate(format: string, date: Date): string {
  const o: {
    [key: string]: number;
  } = {
    "M+": date.getMonth() + 1, // 月份
    "d+": date.getDate(), // 日
    "h+": date.getHours(), // 小时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    "S": date.getMilliseconds() // 毫秒
  };

  if (/(y+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }

  for (const k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1
          ? `${o[k]}`
          : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return format;
}

用法如下图所示:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_37793545/article/details/104699461