格式化时间戳

源码
/** 格式化时间
 *  @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秒

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容