图书机后台管理模块中,由于公司项目需要,需要通过时间来查看设备的网络连接状态,当小于5分钟时需要警告(表格中那一列字体变红)!由于我要返回多个值,所以就通过返回个对象。哈哈,因为会经常遇到时间戳转化成天、时、分、秒,所以这里就总结一下啦!
Date.parse()函数, 方法可解析一个日期时间字符串,并返回 1970/1/1 午夜距离该日期时间的毫秒数。如:Data.parse("2018-01-23 18:07:51.0");
function networkTime(time) { var netConnectTime = parseInt(Date.parse(time)/1000);//网络连接时间 var currentTime = parseInt(new Date().getTime()/1000);//当前时间 var hasUseTime = parseInt(currentTime - netConnectTime); var returnObj = {}; // 1 时 = 3600秒 1分 = 60秒 if (hasUseTime < 60) { if (hasUseTime < 0) { returnObj = {"time":"0秒以前", "flag":false}; }else{ returnObj = {"time":parseInt(hasUseTime)+"秒以前", "flag":false}; } return returnObj; }else if (hasUseTime >= 60 && hasUseTime <= 3600) { if ( hasUseTime > 300) { //大于5分钟标红 returnObj = {"time":parseInt(hasUseTime/60)+"分钟前", "flag":true}; return returnObj; }else { returnObj = {"time":parseInt(hasUseTime/60)+"分钟前", "flag":false}; return returnObj; } }else if (hasUseTime > 3600 && hasUseTime <= 3600*24) { var h = parseInt(hasUseTime/3600); var min = parseInt((hasUseTime - h*3600)/60); returnObj = {"time":h+"小时"+min + "分钟前", "flag":true}; return returnObj; }else if (hasUseTime > 3600*24 ){ var day = parseInt( hasUseTime/ (24*3600) ); var hour = parseInt( (hasUseTime - day*24*3600) / 3600); var minute = parseInt( (hasUseTime - day*24*3600 - hour*3600) /60 ); console.log("day:"+day); console.log("hour:"+hour); console.log("minute:"+minute); /* var day = parseInt(hasUseTime/(3600*24)); //天数 var hour = parseInt(hasUseTime % (60*24)); // hasUseTime % 3600 求余数分钟 var minute = hasUseTime % (3600*24)*/ returnObj = {"time":day+ "天"+hour+"小时"+minute+'分钟前', "flag":true}; return returnObj; } }