小白看到微信小程式的一個格式化時間戳,挺好用的,記錄一下
// 格式化日期時間
const formatTime = date => {
const data = new Date(date);
const year = data.getFullYear()
const month = data.getMonth() + 1
const day = data.getDate()
const hour = data.getHours()
const minute = data.getMinutes()
const second = data.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
// 格式化日期
const formatDate = date => {
const data = new Date(date);
const year = data.getFullYear()
const month = data.getMonth() + 1
const day = data.getDate()
const hour = data.getHours()
const minute = data.getMinutes()
const second = data.getSeconds()
return [year, month, day].map(formatNumber).join('-')
}
// 在單數字前面加0
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
module.exports = {
formatTime: formatTime,
formatDate,
}
複製程式碼