平时在项目开发中,经常会遇到诸多的时间处理,最开始选择moment,后来发现,其实项目中需要处理函数的场景比较单一,没必要引入moment,于是就开始了处理date的漫漫填坑之路。
填坑之旅
坑一
首先看一下上面这段代码,我的本意是生成2018-06-17 00:00:00这个时间,但是运行的结果却是早上8点。那么理清这个的原因就涉及GMT、UTC的概念。
GMT(格林尼治标准时间)是一些欧洲和非洲国家正式使用的时间,UTC是国际标准。这两个时间一般情况是相等的。中国处于东八区,与UTC时间相差8个小时,也就是说UTC时间00:00:00的时候,我们的时间是08:00:00。
为了避免这种现象,对于任何的输入,都统一生成一个UTC时间,那么新建一个date函数,这个Date函数用于根据传入的时间模板,生成一致的时间。’yyyy-MM-dd’格式的时间模板new出来的date是本地时间,所以用正则表达式匹配一下/^\d{4}(-\d{2}){0,2}$/.test(date)
。重写一个Date构造函数,用于根据输入的时间模板生成一致的时间。
var localDate = new Date(date)
if (date && /^\d{4}(-\d{2}){0,2}$/.test(date)) {
let timeZoneOffset = localDate.getTimezoneOffset()
let utcTimeStamp = localDate.getTime() + timeZoneOffset * 60 * 1000
return new Date(utcTimeStamp)
}
坑二
IOS上执行new Date('1990-01-04 09:09:09')
会得到invilaid date。处理方法是对1990-01-04
转换成1990/01/04
的格式
后端为了区分时间和普通的字符串,对时间模板通常会加一个T
分隔时间,如’1990-01-04T10:10:00’。 js移动端运行结果
PC端运行结果
ISO 8601的标准格式是:YYYY-MM-DDTHH:mm:ss.sssZ。T
表示UTC,所以手机端运行出的时间会在加上8个小时的时差。
此外,
考虑到后端用T
只是用于区分普通字符串和时间,所以此处将T
替换成空格。 完整的生成Date的函数
function DateUTC (date) {
let isDate = (typeof date === 'object') && (date instanceof Date)
if (isDate) return date
let localDate
if (Object.prototype.toString.apply(date).slice(-7, -1) === 'String') {
date = date.replace(/T/, ' ').replace(/-/g, '/')
}
try {
localDate = date === undefined ? new Date() : new Date(date)
} catch (e) {
console.error(e)
}
var localDate = new Date(date)
if (date && /^\d{4}(-\d{2}){0,2}$/.test(date)) {
let timeZoneOffset = localDate.getTimezoneOffset()
let utcTimeStamp = localDate.getTime() + timeZoneOffset * 60 * 1000
return new Date(utcTimeStamp)
}
return localDate
}
常用的功能
format,格式化时间
// 默认的格式是 'yyyy-MM-dd'
function format (date, form = 'yyyy-MM-dd') {
date = DateUTC(date)
if (!form) return date
let year = date.getFullYear()
let month = leftPad(date.getMonth() + 1)
let day = leftPad(date.getDate())
let hours = leftPad(date.getHours())
let minutes = leftPad(date.getMinutes())
let seconds = leftPad(date.getSeconds())
return form.replace('yyyy', year).replace('MM', month).replace('dd', day).replace('HH', hours).replace('mm', minutes).replace('ss', seconds)
}
diff,计算两个时间差
/**
*
* @param {*} time1 a Date object or Date params
* @param {*} time2 a Date object or Date params
* @param {*} unit can be one of ['year', 'month', 'day', 'hour', 'minute', 'second']
* @param {*} exact get exact day diff
*/
function diff (time1, time2, unit='day', exact = false) {
let date1 = DateUTC(time1)
let date2 = DateUTC(time2)
if (unit === 'year') {
return date2.getFullYear() - date1.getFullYear()
}
if (unit === 'month') {
let diffYear = date2.getFullYear() - date1.getFullYear()
return (date2.getMonth() - date1.getMonth()) + 12 * diffYear
}
if (!exact && unit === 'day') {
date1 = DateUTC(format(date1, 'yyyy-MM-dd'))
date2 = DateUTC(format(date2, 'yyyy-MM-dd'))
}
let timeStampUnit = getTimeStampUnit(unit)
return parseInt((date2.getTime() - date1.getTime()) / timeStampUnit)
}
dateFrom,根据给定的时间time,返回另一个时间
/**
*
* @param {*} date a Date object or Date params
* @param {*} diff
* @param {*} unit can be one of ['year', 'month', 'day', 'hour', 'minute', 'second']
* for example: dateFrom('2012-02-29', 12, 'month') // Fri Mar 01 2013 00:00:00 GMT+0800 (CST)
*/
function dateFrom(time, diff, unit='day') {
let date = DateUTC(time)
if (unit === 'year') {
let year = date.getFullYear() + diff
return DateUTC(date.setFullYear(year))
}
if (unit === 'month') {
let month = date.getMonth() + diff
return DateUTC(date.setMonth(month))
}
let timeStampUnit = getTimeStampUnit(unit)
return DateUTC(date.getTime() + diff * timeStampUnit)
}
dateTemplate,时间模板函数
/** * a date template which can help you new a Date */
function dateTemplate ({ date, diff, form, unit } = {}) {
var _date = !date ? DateUTC() : date
if (diff) {
_date = dateFrom(_date, diff, unit)
}
if (form) {
_date = format(_date, form)
}
return _date
}
完整代码
(function ($) {
function DateUTC (date) {
if (arguments.length === 0) return new Date()
if (isDate(date)) return date
let localDate
if (Object.prototype.toString.apply(date).slice(-7, -1) === 'String') {
date = date.replace(/T/, ' ').replace(/-/g, '/')
}
try {
localDate = new Date(date)
} catch (e) {
console.error(e)
}
// 匹配yyyy-MM-dd | yyyy-MM
if (date && /^\d{4}(-\d{2}){0,2}$/.test(date)) {
let timeZoneOffset = localDate.getTimezoneOffset()
let utcTimeStamp = localDate.getTime() + timeZoneOffset * 60 * 1000
return new Date(utcTimeStamp)
}
return localDate
}
function format (date, form = 'yyyy-MM-dd') {
date = DateUTC(date)
if (!form) return date
let year = date.getFullYear()
let month = leftPad(date.getMonth() + 1)
let day = leftPad(date.getDate())
let hours = leftPad(date.getHours())
let minutes = leftPad(date.getMinutes())
let seconds = leftPad(date.getSeconds())
return form.replace('yyyy', year).replace('MM', month).replace('dd', day).replace('HH', hours).replace('mm', minutes).replace('ss', seconds)
}
/** * * @param {*} time1 a Date object or Date params * @param {*} time2 a Date object or Date params * @param {*} unit can be one of ['year', 'month', 'day', 'hour', 'minute', 'second'] * @param {*} exact get exact day diff */
function diff (time1, time2, unit='day', exact = false) {
let date1 = DateUTC(time1)
let date2 = DateUTC(time2)
if (unit === 'year') {
return date2.getFullYear() - date1.getFullYear()
}
if (unit === 'month') {
let diffYear = date2.getFullYear() - date1.getFullYear()
return (date2.getMonth() - date1.getMonth()) + 12 * diffYear
}
if (!exact && unit === 'day') {
date1 = DateUTC(format(date1, 'yyyy-MM-dd'))
date2 = DateUTC(format(date2, 'yyyy-MM-dd'))
}
let timeStampUnit = getTimeStampUnit(unit)
return parseInt((date2.getTime() - date1.getTime()) / timeStampUnit)
}
/** * * @param {*} date a Date object or Date params * @param {*} diff * @param {*} unit can be one of ['year', 'month', 'day', 'hour', 'minute', 'second'] * for example: dateFrom('2012-02-29', 12, 'month') // Fri Mar 01 2013 00:00:00 GMT+0800 (CST) */
function dateFrom(time, diff, unit='day') {
let date = DateUTC(time)
if (unit === 'year') {
let year = date.getFullYear() + diff
return DateUTC(date.setFullYear(year))
}
if (unit === 'month') {
let month = date.getMonth() + diff
return DateUTC(date.setMonth(month))
}
let timeStampUnit = getTimeStampUnit(unit)
return DateUTC(date.getTime() + diff * timeStampUnit)
}
/** * a date template which can help you new a Date */
function dateTemplate ({ date, diff, form, unit } = {}) {
var _date = !date ? DateUTC() : date
if (diff) {
_date = dateFrom(_date, diff, unit)
}
if (form) {
_date = format(_date, form)
}
return _date
}
function isDate (date) {
return date instanceof Date
}
function leftPad (val) {
return val.toString().padStart(2, '0')
}
function getTimeStampUnit (unit) {
switch (unit) {
case 'day':
return 1000 * 3600 * 24
case 'hour':
return 1000 * 3600
case 'minute':
return 1000 * 60
case 'second':
return 1000
break
default:
return 1
}
}
$.format = format
$.diff = diff
$.DateUTC = DateUTC
$.dateFrom = dateFrom
$.dateTemplate = dateTemplate
})(window.$);
今天的文章Date填坑记分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/13421.html