首先调用这个函数的时候,第一个参数需要传入需要格式化的时间戳。
如果要得到制定的日期类型,还要传入的type类型,来对日期进行格式化,得到想要的日期格式。
formaterDate(cellValue, type) {
// cellValue为传入的需要格式化的时间戳,type为传入的需要格式化得到的日期类型
if (cellValue == null || cellValue === '') {
// 如果没有传入了需要格式化的时间戳
return ''
} else {
// 如果传入了需要格式化的日期值:cellValue
var date = new Date(cellValue)
// 年
var year = date.getFullYear()
// 月
var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
// 日
var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
// 时
var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
// 分
var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
// 秒
var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
if (type === 'year') {
// 如果需要格式化,得到年份
return year
} else if (type === 'month') {
// 如果需要格式化,得到月份
return month
} else if (type === 'date') {
// 如果需要格式化,得到年月日
return year + '-' + month + '-' + day
} else if (type === 'hours') {
// 如果只需要格式化,得到小时
return hours + ':00'
} else if (type === 'HMS') {
// 如果只需要格式化,得到时分秒
var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
return hours + ':' + minutes + ':' + seconds
} else if (type === 'seconds') {
// 如果需要格式化,得到年月日时分
return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes
} else {
// 如果只需要格式化,得到年月日时分秒
return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}
}
}