去年做的积分商城的小项目,根据项目需要封装了这个时间处理的方法,可以根据传入的格式返回对应格式得到时间。以及进行时间比较。
Date.prototype.Format = function(format) {
let o = {
'M+': this.getMonth() + 1,
'd+': this.getDate(),
'h+': this.getHours() % 12 === 0 ? 12 : this.getHours() % 12,
'H+': this.getHours(),
'm+': this.getMinutes(),
's+': this.getSeconds(),
'q+': Math.floor((this.getMonth() + 3) / 3),
'S+': this.getMilliseconds()
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ?
(o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return format;
};
export default {
/**
* 时间戳转格式化日期
* @param time {Number,String}
* @param format
* @returns {string}
*/
formatDateByCustom(time, format) {
if (typeof time === 'string') {
if (time.indexOf('-') > -1) {
time = time.replace(/-/g, '/');
}
}
return new Date(time).Format(format);
},
/**
* 时间戳转格式化日期yyyy-MM-dd HH:mm:ss
* @param time {Number,String}
* @returns {string}
*/
formatDate(time) {
return this.formatDateByCustom(time, 'yyyy-MM-dd HH:mm:ss');
},
/**
* 时间戳转格式化日期yyyy-MM-dd
* @param time {Number,String}
* @returns {string}
*/
formatDateOfDate(time) {
return this.formatDateByCustom(time, 'yyyy-MM-dd');
},
/**
* 2个日期之间的比较
* @param date1 {String}
* @param date2 {String}
*/
compareDate(date1, date2) {
if (date1.indexOf('-') > -1) {
date1 = date1.replace(/-/g, '/');
}
if (date2.indexOf('-') > -1) {
date2 = date2.replace(/-/g, '/');
}
let time1 = new Date(date1);
let time2 = new Date(date2);
return time1.getTime() - time2.getTime();
},
/**
* 跟当前日期的比较
* @param date {String}
*/
compareDateToNow(date) {
if (date.indexOf('-') > -1) {
date = date.replace(/-/g, '/');
}
let now = new Date();
let time = new Date(date);
return now.getTime() - time.getTime();
},
/**
* 是否同一天
* @param date
* @returns {boolean}
*/
isTheSameDay(date) {
if (date.indexOf('-') > -1) {
date = date.replace(/-/g, '/');
}
let now = new Date();
let regDate = new Date(date);
return regDate.getDate() === now.getDate() &&
regDate.getMonth() === now.getMonth() &&
regDate.getFullYear() === now.getFullYear();
}
};