格式化时间戳

源码
/** 格式化时间
 *  @param {string} date 需要格式化的时间
 *  @param {string} fmt 想要格式化的格式
 *  formatDate(new Date(时间戳), 'yyyy-MM-dd hh:mm:ss')
 */
export const formatDate = (date, fmt) => {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length)
      )
    }
  }
  return fmt
}
调用
import { formatDate } from ./date.js

const date = new Date().valueOf //变成时间戳传入后台用

console.log(date) //1559322355621

const formatDate = formatDate(new Date(date),'yyyy-MM-dd hh-mm-ss')

console.log(formatDate) //2019-06-01 01-06-20

const chineseDate =  formatDate(new Date(date),'yyyy年MM月dd日 hh时mm分ss秒')

console.log(chineseDate) //2019年06月01日 01时08分01秒

猜你喜欢

转载自blog.csdn.net/weixin_34377065/article/details/90882700