日常项目中常常会对后端返回的时间格式进行处理,以下几个时间处理的函数
- 时间格式化
Date.prototype.Formate = function (formate) {
var agrs= {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(formate)) formate= formate.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in agrs)
if (new RegExp("(" + k + ")").test(formate))
formate= formate.replace(RegExp.$1, (RegExp.$1.length == 1) ? (agrs[k]) : (("00" + agrs[k]).substr(("" + agrs[k]).length)));
return formate;
}
//测试调用
console.log(new Date().Formate('yyyy-MM-dd hh:mm:ss'));
//2018-12-17 16:54:46
console.log(new Date().Formate('yyyy-MM-dd'));
// 2018-12-17
console.log(new Date().Formate('yyyy年MM月dd日 hh时mm分ss秒');
//2018年12月17日 16时54分46秒
console.log(new Date(1545036827000).Formate('yyyy年MM月dd日 hh时mm分ss秒');
// 2018年12月17日 16时53分47秒
- 倒计时
var timer=null;
Date.prototype.GetCountDown=function(){
var that=this;
var agrs={};
timer=setInterval(function(){
var startTime=Date.parse(that);
var nowTime=Date.parse(new Date()),
time=Math.abs(nowTime-startTime),
d=Math.floor(time/1000/60/60/24),//日
h=Math.floor(time/1000/60/60%24),//小时
m=Math.floor(time/1000/60%60), //分
s=Math.floor(time/1000%60);//秒
d=d<10?'0'+d:d;
h=h<10?'0'+h:h;
m=m<10?'0'+m:m;
s=s<10?'0'+s:s;
countTime= d+'天'+h+'小时'+m+'分钟'+s+'秒'
console.log(countTime);
},1000)
}
//调用
new Date('2019-1-1').GetCountDown();
- 显示多长时间之前发布(获取指定时间到现在的时间差)
function getDateDiff(time) {
var date = typeof time === 'number' ? new Date(time) : new Date((time || '').replace(/-/g, '/'));
var diff = (new Date().getTime() - date.getTime()) / 1000;
var dayDiff = Math.floor(diff / 86400);
var isValidDate = Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime());
if (!isValidDate) {
console.error('not a valid date');
}
var formatDate = function (date) {
var today = new Date(date);
var year = today.getFullYear();
var month = ('0' + (today.getMonth() + 1)).slice(-2);
var day = ('0' + today.getDate()).slice(-2);
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
};
if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) {
return formatDate(date);
}
return (
(dayDiff === 0 &&
((diff < 60 && '刚刚') ||
(diff < 120 && '1 分钟前') ||
(diff < 3600 && Math.floor(diff / 60) + ' 分钟前') ||
(diff < 7200 && '1 小时前') ||
(diff < 86400 && Math.floor(diff / 3600) + ' 小时前'))) ||
(dayDiff === 1 && '昨天') ||
(dayDiff < 7 && dayDiff + ' 天前') ||
(dayDiff < 31 && Math.ceil(dayDiff / 7) + ' 周前')
);
}
//测试
getDateDiff('2018-12-10 12:00:00') //"2 周前"
getDateDiff('2018-12-18 12:00:00') //"昨天"
getDateDiff('2018-12-19 12:00:00') //"2 小时前"
getDateDiff('2018-12-19 14:05:00') // 1分钟前