每個網(wǎng)站都會有時間相關的展示琅捏,例如文章、新聞的發(fā)布時間孙蒙,時間選擇器的時間展示项棠,顯示當天時間等等】媛停基本上后端數(shù)據(jù)庫存儲的都是Unix時間戳香追,前端需要將它轉(zhuǎn)換成對應格式的字符串
格式類似于2018.09.08
,18-09-08
,09-08 16:37
, 2018-09-08 16:37:00
等等等。如果網(wǎng)站的時間展示格式是統(tǒng)一的坦胶,你完全可以定一個函數(shù)來轉(zhuǎn)換對應的格式透典,如下
// 轉(zhuǎn)換成 ‘2018-09-08 16:37:00’
function dateFormat(time) {
const date = new Date(time * 1000)
// 不足倆位補0
const fillZero = number => number > 9 ? number : '0' + number
const year = date.getFullYear()
const month = fillZero(date.getMonth() + 1)
const day = fillZero(date.getDate())
const hours = fillZero(date.getHours())
const minutes = fillZero(date.getMinutes())
const seconds = fillZero(date.getSeconds())
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
但當你網(wǎng)站有一區(qū)域的時間展示不需要時分秒的時候,這時也可以通過將函數(shù)增加參數(shù)顿苇,來返回不同格式:
// isHours 參數(shù)代表是否需要時分秒
function dateFormat(time, isHours) {
// .....
if (isHours) {
return `${year}-${month}-${day}`
} else {
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
}
如果有的情況需要將連接符改為'.'峭咒,類似于2018.09.08
,再定義個連接符參數(shù),雖然也可以解決問題纪岁,但當又有其他格式(類似于只需要年份后倆位18.09.08
, 不需要補02018.9.8
)時,你的dateFormat
函數(shù)就會臃腫起來凑队,傳的參數(shù)也會越來越多。
想要寫一個通用的時間轉(zhuǎn)換函數(shù)是可以借鑒成熟插件的方法幔翰,傳入一個格式參數(shù)('YYYY-MM-dd HH:mm:ss'
)漩氨,來轉(zhuǎn)換對應格式的字符串短条。這時就可以使用正則恢准,去匹配替換格式中的字母莺治。
/**
* 將時間戳轉(zhuǎn)換為相對應格式時間
* @param {時間戳} time
* @param {時間格式} format
*/
function dateFormat(time, format) {
const date = new Date(time * 1000)
const pattern = {
'Y+': date.getFullYear(),
'M+': date.getMonth() + 1,
'D+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (var k in pattern) {
const regexp = new RegExp(`(${k})`)
const replaceFn = (match) => {
// 當匹配到倆個YY或以上時裆赵,替換成年份
if (match.includes('YY')) {
return ('' + pattern[k]).substr(4 - match.length)
}
// 其他的都判斷匹配長度是否大于1模狭,大于則補充0沐扳,否則直接輸出
const fillZero = num => num > 9 ? num : '0' + num
return match.length === 1 ? pattern[k] : fillZero(pattern[k])
}
// 將字符串按照正則匹配替換成函數(shù)返回值
format = format.replace(regexp, replaceFn)
}
return format
}
上面函數(shù)首先定義了格式參數(shù)需要的正則和對應的取值操作挠将,循環(huán)遍歷正則對象耕姊,將匹配出來的字符串替換成時間即可婚陪。其中String.replace
第一個參數(shù)可以是正則蚓耽,第二個參數(shù)可以是返回替換字符串的函數(shù)渠牲,接受的參數(shù)是匹配到的字符傳。傳送門
這個函數(shù)還有許多不足步悠,其中沒有對不允許的格式進行判斷签杈,而且只能轉(zhuǎn)換對應時間,不能通過時間戳轉(zhuǎn)換前幾天鼎兽,或幾周前的時間答姥。如果業(yè)務涉及到復雜的時間轉(zhuǎn)換,可以使用以下幾種成熟的時間插件谚咬。例如:date-fns鹦付、moment、dayjs