平時在專案開發中,經常會遇到諸多的時間處理,最開始選擇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移動端執行結果
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.$);
複製程式碼