时间格式化函数

330 阅读1分钟

参数

  • date 要格式化的时间
  • format 进行格式化的模式

支持的模式字母有:

字母含义
y
M月(1 - 12)
d日(1 - 31)
h时(0 - 23)
m分(0 - 59)
s秒(0 - 59)
q季度(1 - 4)
S毫秒(0 - 999)

说明

举例的时间为:2020年1月1日 08:05:30

format 的格式可以像下面这样:

  • yyyy-MM-dd 返回 2020-01-03
  • yy-M-d 返回 20-1-3
  • yy-M-d hh:mm:ss 返回 20-1-3 08:05:30
  • yy-M-d h:m:s 返回 20-1-3 8:5:30

年份:可以返回末尾两位; 月/日/时/分/秒:可以始终返回两位数(用 0 在前面补位)或者一位数。

代码

/**
 * 对日期进行格式化:
 * 示例:
 * yyyy-MM-dd (年-月-日), 或 yy-M-d (年-月-日).
 * @param date 要格式化的日期
 * @param {string} format 进行格式化的模式字符串
 * @return {string}
 * @author yanis.wang
 * @see http://yaniswang.com/frontend/2013/02/16/dateformat-performance/
 * 支持的模式字母有:
 * y: 年
 * M: 月
 * d: 日
 * h: 时
 * m: 分
 * s: 秒
 * q: 季度
 * S: 毫秒
 */
function dateFormat(date, format) {
  if (typeof date === 'string' && /^\d+$/.test(date)) {
    date = parseInt(date);
  }

  date = new Date(date);
  if (date.toString() === 'Invalid Date') {
    throw 'Error, parameter date is not valid: Invalid Date.';
  }

  var map = {
    "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(), // 毫秒
  };

  format = format.replace(
    /([yMdhmsqS])+/g,
    function (match, p, offset, string) {
      var v = map[p];
      if (v !== undefined) {
        // 月/日/时/分/秒 的格式为 xx 时始终返回两位数,若只有一位,用 0 在前面补位
        if (match.length > 1 && p !== 'S') {
          v = '0' + v;
          v = v.substring(v.length - 2);
        }
        return v;
      } else if (p === 'y') {
        // 处理 年
        // 传入年的格式为 yy 返回年份末尾两位
        if (match.length === 2) {
          return (date.getFullYear() + '').substring(2);
        } else {
          // yyyy/yyy/y 返回完整的年
          return (date.getFullYear() + '');
        }
      }
    });
  return format;
}