高性能日期格式化插件

54 阅读1分钟

介绍

自我觉得是高性能的, 便捷的, 主要使用了字符串的截取来实现, 只能转为以 '-' 隔开的, 不去处理'/'分割的, 有那种需求, 可以在以下代码上改.


/**
 * 快速获取日期
 * @param date 日期, 日期字符串
 * @param fmt 格式化固定几种格式
 * 年; 年月; 年月日; 年月日时分; 年月日时分秒;
 * @return {*}
 */
export function getDate(date, fmt = '年月日时分秒') {
  if (isNaN(Date.parse(date))) {
    // 没传日期, 格式化当前日期
    fmt = date || fmt;
    date = new Date();
  } else {
    // 处理'2020-12-12' 直接new Date(), 变成八点
    date = new Date(isNaN(date) && date.length < 11 ? new Date(date) - 28800 * 1000 : date);
  }
  // '2025-03-21T01:47:09.945Z'
  let dateStr = new Date(+date + 28800 * 1000).toISOString().replace('T', ' ').slice(0, -5);
  let map = {
    年: 4,
    年月: 7,
    年月日: 10,
    年月日时分: -3,
    年月日时分秒: undefined,
  };
  return dateStr.slice(0, map[fmt]);
}

注册

注册到window和vue的原型链上面, 在代码中可以使用 this.$getDate() 进行调用, 可以在vue的data直接调用.

使用

this.$getDate(); // '2025-03-27 15:57:14'
this.$getDate('年月'); // '2025-03'
this.$getDate('2020-12', '年月日'); // '2020-12-01'
this.$getDate('2020-12', '年月日时分秒'); // '2020-12-01 00:00:00'
this.$getDate('2020-12-12 12:12', '年月'); // '2020-12'