平常開發中,常常會遇到如下對於時間(日期)的操做需求:前端
路人甲大佬: 爲啥不用day.js或者moment.js這些現成的庫git
如今最流行的day.js輕量庫以及moment.js均可以實現以上功能,可是moment.js有12kb大小,day.js僅僅2kb大小,爲了時間數據的格式化引入day.js徹底沒有問題,可是後兩個功能的實現須要引入moment.js,做者認爲還不如本身寫一套。github
此功能無非調用原生js的Date對象的 getFullYear() 、 getMonth() 、 getDate() 等方法獲取值以後的拼接,在這裏不作贅述後端
以前做者開發中只碰到了比較兩段日期的前後順序做校驗,因此採起了如下本辦法ui
Demo 1 - 比較兩天大小(笨辦法)spa
const day1 = '2018-11-12'
const day2 = '2018-10-22'
function compareDate (day1, day2) {
const day1Num = parseInt((day1.split('-').join('')), 10)
const day2Num = parseInt((day2.split('-').join('')), 10)
const differenceCount = day2Num - day1Num
console.log(differenceCount) // -90
let result = differenceCount === 0 ?
'the same day' : differenceCount > 0 ?
'the day1 is earlier than the day2' :
'the day2 is earlier than the day1'
return result
}
console.log(compareDate(day1, day2)) // the day2 is earlier than the day1
複製代碼
問題:這種方法雖然達到了比較兩個日期的大小,可是其中的差值是須要進一步處理的,不是很嚴謹,並且涉及要計算小時的差值,則徹底沒有辦法使用code
Demo 1 - 比較兩天大小(利用換算成距 1970 年 1 月 1 日之間的毫秒數)orm
function newCompareDate (day1, day2) {
const day1Date = new Date(day1)
const day1Time = day1Date.getTime()
const day2Date = new Date(day2)
const day2Time = day2Date.getTime()
const differenceCount = day2Time - day1Time
console.log(differenceCount) // -1814400000
let result = differenceCount === 0 ?
'the same day' : differenceCount > 0 ?
'the day1 is earlier than the day2' :
'the day2 is earlier than the day1'
return result
}
console.log(newCompareDate(day1, day2)) // the day2 is earlier than the day1
複製代碼
利用js提供的getTime()方法換算成「距 1970 年 1 月 1 日之間的毫秒數」而後進行差值計算,若是要獲得小時數或者天數,則進行進一步計算便可對象
demo 2ip
function getAllDateArr (begin, end) {
let arr = []
let beginArr = begin.split('-')
let endArr = end.split('-')
let beginDate = new Date()
beginDate.setUTCFullYear(parseInt(beginArr[0], 10), parseInt(beginArr[1], 10) - 1, parseInt(beginArr[2], 10))
let endDate = new Date()
endDate.setUTCFullYear(parseInt(endArr[0], 10), parseInt(endArr[1], 10) - 1, parseInt(endArr[2], 10))
let beginSec = db.getTime() - 24 * 60 * 60 * 1000
let endSec = de.getTime()
for (let i = beginSec; i < endSec; i++) {
i = i + 24 * 60 * 60 * 1000
// 使用day.js格式化日期
arr.push(dayjs(new Date(i)).format('YYYY-MM-DD'))
}
return arr
}
getAllDateArr('2018-11-12', '2018-12-12')
複製代碼
以上功能除了day.js以外,其餘功能若是引入moment.js則差很少須要14kb內存大小,但本身實現不到20行代碼則能夠實現功能,因此依賴第三方庫有時候能夠考慮本身手動實現。
做者在以前的一個國際項目中碰到一個問題:在國內前端處理好數據發送到後端,後端存儲後若是在其餘時區獲取使用此時間,會出現時間顯示的偏差,緣由是由於先後端時區不統一的問題,當時的解決方案是前端解決,前端只要在存儲及顯示的時候,獲取本地的時區而後進行時間的換算便可。
BY--LucaLJX (LucaLJX的github)