formatDate.js
/**
*
* 将日期格式化成指定格式的字符串
* @param { Number,String } time 时间戳或new Date()可接受的参数,不传默认当前时间
* @param { String } fmt 目标字符串格式,支持的字符有:y,M,d,q,w,H,h,m,S,默认:yyyy-MM-dd HH:mm:ss
* @returns 返回格式化后的日期字符串
*/
function (time = Date.now(), fmt = 'yyyy-MM-dd HH:mm:ss') {
const date = new Date(time)
if (date === 'Invalid Date') return time
const obj = {
'y': date.getFullYear(), // 年份,注意必须用getFullYear
'M': date.getMonth() + 1, // 月份,注意是从0-11
'd': date.getDate(), // 日期
'q': Math.floor((date.getMonth() + 3) / 3), // 季度
'w': date.getDay(), // 星期,注意是0-6
'H': date.getHours(), // 24小时制
'h': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 12小时制
'm': date.getMinutes(), // 分钟
's': date.getSeconds(), // 秒
'S': date.getMilliseconds() // 毫秒
}
const week = ['天', '一', '二', '三', '四', '五', '六']
for (const i in obj) {
fmt = fmt.replace(new RegExp(i + '+', 'g'), function (m) {
let val = obj[i] + ''
if (i === 'w') return (m.length > 2 ? '星期' : '周') + week[val]
for (let j = 0, len = val.length; j < m.length - len; j++) val = '0' + val
return m.length === 1 ? val : val.substring(val.length - m.length)
})
}
return fmt
};
如果用于Vue中,可全局注册改组件,全局使用
import Vue from 'vue'
import { formatDate } from './utils'
// 时间戳转日期
Vue.filter('fmt', (timestamp, fmt = 'yyyy-MM-dd HH:mm:ss') => {
if (timestamp) {
return formatDate(timestamp, fmt)
} else {
return ''
}
})
使用:
// PC端 在element-ui中使用,格式化时间戳为 2018-01-02 格式
<el-table-column align="center" sortable prop="sumdata" label="申请总时间">
<template slot-scope="scope">
{{scope.row.sumdata | fmt('yyyy-MM-dd')}}
</template>
</el-table-column>