function formatTime(timestamp, type = “date”) {
var date = new Date(timestamp);
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
if (type == “date”) {
return [year, month, day].map(formatNumber).join(’-’);
} else if (type == “all”) {
return [year, month, day].map(formatNumber).join(’-’) + ’ ’ + [hour, minute, second].map(formatNumber).join(’:’)
} else if (type == “time”) {
return [hour, minute, second].map(formatNumber).join(’:’)
} else if (type == “time2”) {
return [hour, minute].map(formatNumber).join(’:’)
} else if (type == ‘month’) {
return [month, day].map(formatNumber).join(’-’);
}
}
/*niu 封装时间戳格式化辅助,将年月日先转为字符串,再判断是否加0/
function formatNumber(n) {
n = n.toString()
return n[1] ? n : ‘0’ + n
}
formatTime(1236547891,‘all’) // 2019-11-02 03:11:11
formatTime(1236547891,‘time’) // 03:11:22
formatTime(1236547891,‘time2’) // 03:11
formatTime(1236547891,‘month’) // 03-03
formatTime(1236547891,‘date’) // 2019-11-02
复制代码