平常开发中,常常会遇到如下对于时间(日期)的操做需求:前端
路人甲大佬: 为啥不用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)