1.時間差計算
var startDate = "2016-06-06"; var endDate = "2016-08-08"; var start=new Date(startDate.replace("-", "/").replace("-", "/")); var end=new Date(endDate.replace("-", "/").replace("-", "/")); if (startDate != "" || endDate != "") { if (startDate != "" && endDate != "" && endDate.length > 0 && start <= end) { var sjc=end.getTime()-start.getTime(); //時間差的毫秒數 var days=Math.floor(sjc/(24*3600*1000)); //計算出相差天數 var leave1=sjc%(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); //計算相差秒數 alert(" 相差 "+days+"天 "+hours+"小時 "+minutes+" 分鍾"+seconds+" 秒"); var year1 = startDate.substr(0,4); var year2 = endDate.substr(0,4); var month1 = startDate.substr(5,2); var month2 = endDate.substr(5,2); var len=(year2-year1)*12+(month2-month1); //計算出相差月份 }else { alert("請輸入正確的時間范圍"); return false; } }
2.時間格式化
/** * 日期格式化 * date:日期對象 * format:時間格式 * 引用 : deteFormat(new Date("2016-05-05 12:23:26"),"yyyy-MM-dd HH:mm:ss") */ dateFormat:function (date,format) { //author: meizz var o = { "M+": date.getMonth() + 1, //月份 "d+": date.getDate(), //日 "h+": date.getHours(), //小時 "m+": date.getMinutes(), //分 "s+": date.getSeconds(), //秒 "q+": Math.floor((date.getMonth() + 3) / 3), //季度 "S": date.getMilliseconds() //毫秒 }; if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var 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; }