js时间相关常用封装
JS计算两个日期时间差,天 小时 分 秒格式
function diffTime(startDate,endDate) { startDate= new Date(startDate); endDate = new Date(endDate); var diff=endDate.getTime() - startDate.getTime();//时间差的毫秒数 //计算出相差天数 var days=Math.floor(diff/(24*3600*1000)); //计算出小时数 var leave1=diff%(24*3600*1000); //计算天数后剩余的毫秒数 var hours=Math.floor(leave1/(3600*1000)); //计算相差分钟数 var leave2=leave1%(3600*1000); //计算小时数后剩余的毫秒数 var minutes=Math.floor(leave2/(60*1000)); //计算相差秒数 var leave3=leave2%(60*1000); //计算分钟数后剩余的毫秒数 var seconds=Math.round(leave3/1000);
var returnStr = seconds + "秒"; if(minutes>0) { returnStr = minutes + "分" + returnStr; } if(hours>0) { returnStr = hours + "小时" + returnStr; } if(days>0) { returnStr = days + "天" + returnStr; } return returnStr;
}
获取当前时间
function getNowTime() { var date = new Date(); this.year = date.getFullYear(); this.month = date.getMonth() + 1; this.date = date.getDate(); this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); var currentTime = this.year + '-' + this.month + '-' + this.date + ' ' + this.hour + ':' + this.minute + ':' + this.second; return currentTime; }