最近做项目,要使用JS做个功能:
显示时间 当天消息时间显示精确到分钟当天以前消息精确到日
在网络上找了很久,都没找到自己想要的,唉,自己动手,丰衣足食!
话不多说,上代码!
//当天时间显示时分,不是当天时间显示月日
function format(obj){
var date1 = new Date(obj) //要对比的时间obj
//判断时间能不能转换,主要是为了兼容ios,ios中要转换只能-换成/
date1 = date1.getFullYear() > 0 ? date1 : new Date(Date.parse(obj.replace(/-/g, "/")));
var date2 = new Date(); //获取当前时间对象
var num = 24*60*60*1000 ; //一天的毫秒数
var cha = date2.getTime() - date1.getTime(); //两个时间的毫秒差
if(cha > 0){
if(cha > num){
return notToday(date1);
}else if(date1.getDate() != date2.getDate()){
return notToday(date1);
}else {
return today(date1);
}
}else if(cha == 0){
return today(date1);
}
}
function notToday(date){
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
return month + '-' + strDate;
}
function today(date){
var hour = date.getHours();
if(hour >= 0 && hour <= 9){
hour = "0" + hour;
}
var minite = date.getMinutes();
if(minite >= 0 && minite <= 9){
minite = "0" + minite;
}
return hour + ':' + minite;
}