前端小菜鸟

简单的时间格式化dateFormat

2023/05/02
319
0

简单的直接格式化dateFormat

/**
 * 日期格式化
 * @param format {string}
 * @param date {Date}
 * @returns {string}
 */
export function dateFormat(format = 'yyyy-MM-dd HH:mm:ss', date = new Date()) {
  const object: Record<string, number> = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };
  const y_regexp = /(y+)/;
  if (y_regexp.test(format)) {
    const searchValue = (format.match(y_regexp) || [])[1] || '';
    const replaceValue = (date.getFullYear() + '').substring(
      4 - searchValue.length,
    );
    format = format.replace(searchValue, replaceValue);
  }
  for (const key in object) {
    const k_regexp = new RegExp('(' + key + ')');
    if (k_regexp.test(format)) {
      const searchValue = (format.match(k_regexp) || [])[1] || '';
      const replaceValue =
        searchValue.length === 1
          ? String(object[key])
          : ('00' + object[key]).substring(('' + object[key]).length);
      format = format.replace(searchValue, replaceValue);
    }
  }
  return format;
}