項目中經常需要把數據轉換,把經常用到的做過總結:
一、時間格式化
export function 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
}
二、分鍾數轉換為小時+分鍾
export function changeHourMinutestr (str) {
let hours = Math.floor(str / 60).toString()
let minutes = (str % 60).toString()
if (str !== '0' && str !== '' && str !== null) {
return hours + '時' + (minutes.length < 2 ? '0' + minutes : minutes) + '分'
} else {
return ''
}
}
三、計算天數差的函數
export function getDateDiff(start, end){
if (!end) {
return '借閱中'
}
let aDate, oDate1, oDate2, iDays
aDate = start.split("-")
oDate1 = new Date(aDate[0] + '/' + aDate[1] + '/' + aDate[2]) //轉換為2016/12/18格式
aDate = end.split("-")
oDate2 = new Date(aDate[0] + '/' + aDate[1] + '/' + aDate[2])
iDays = Math.ceil(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24) //把相差的毫秒數轉換為天數
return iDays
}
