时间格式化函数,TS版本

  • Post author:
  • Post category:其他


export const dateFormat = (
  dateStr: string | Date,
  formatter: string = 'yyyy-MM-dd',
) => {
  let date = dateStr
  if (typeof date === 'string') {
    date = new Date(dateStr)
  }
  let o = {
    '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(formatter)) {
    formatter = formatter.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length),
    )
  }
  for (const [k, v] of Object.entries(o)) {
    if (new RegExp('(' + k + ')').test(formatter)) {
      formatter = formatter.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? '' + v : ('00' + v).substr(('' + v).length),
      )
    }
  }
  return formatter
}



版权声明:本文为qq_36493878原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。