Javascript计算时间差的函数分享

/* * 获得时间差,时间格式为 年-月-日 小时:分钟:秒 或者 年/月/日 小时:分钟:秒 * 其中,年月日为全格式,例如 : 2010-10-12 01:00:00 * 返回精度为:秒,分,小时,天 */ function GetDateDiff(startTime, endTime, diffType) { //将xxxx-xx-xx的时间格式,转换为 xxxx/xx/xx的格式 startTime = startTime.replace(/\-/g, "https://www.jb51.net/"); endTime = endTime.replace(/\-/g, "https://www.jb51.net/"); //将计算间隔类性字符转换为小写 diffType = diffType.toLowerCase(); var sTime = new Date(startTime); //开始时间 var eTime = new Date(endTime); //结束时间 //作为除数的数字 var divNum = 1; switch (diffType) { case "second": divNum = 1000; break; case "minute": divNum = 1000 * 60; break; case "hour": divNum = 1000 * 3600; break; case "day": divNum = 1000 * 3600 * 24; break; default: break; } return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum)); }

调用方法也很简单:
GetDateDiff("2010-10-11 00:00:00", "2010-10-11 00:01:40", "day")
这个是计算天数
GetDateDiff("2010-10-11 00:00:00", "2010-10-11 00:01:40", "seond")是计算秒数

下面脚本之家小编再为大家分析一个不错的

<html> <script type="text/javascript"> alert(dealDate("2018-01-20","2018-01-28")); //提示前面的日期小于后面的日期 function dealDate(date1,date2){ date1 = new Date(date1);//如果传进来的是"yyyy-MM-dd"形式的字符串 date2 = new Date(date2); var year1 = date1.getFullYear(); var month1 = date1.getMonth()+1; var day1 = date1.getDate(); var dateMax1 = new Date(year1,month1,0); var dayMax1 = dateMax1.getDate(); var year2 = date2.getFullYear(); var month2 = date2.getMonth()+1; var day2 = date2.getDate(); var dateMax2 = new Date(year2,month2,0); var dayMax2 = dateMax2.getDate(); if(day1==dayMax1&&day2==dayMax2){ //开始日期和结束日期都是月底 //直接计算月份差,推算几年几个月 var res = (year2-year1)*12+(month2-month1);//月份差 var difYear = Math.floor(res/12); var difMonth = res%12; return ((difYear!=0)?(difYear+"年"):"")+difMonth+"个月"; }else if(day1==dayMax1&&day2<dayMax2){ //开始日期是月底,结束日期不是 //计算开始日期到结束日期上一个月的月底,再加上结束日期的天数 var month3 = month2-1; var res = (year2-year1)*12+(month3-month1);//月份差 var difYear = Math.floor(res/12); var difMonth = res%12; var difDay = day2; return ((difYear!=0)?(difYear+"年"):"")+((difMonth!=0)?(difMonth+"个月"):"")+difDay+"天"; }else if(day1<dayMax1&&day2<dayMax2){ //开始日期和结束日期都不是月底 //情况1,day1<day2 if(day1<=day2){ var res = (year2-year1)*12+(month2-month1);//月份差 var difYear = Math.floor(res/12); var difMonth = res%12; var difDay = day2-day1; return ((difYear!=0)?(difYear+"年"):"")+((difMonth!=0)?(difMonth+"个月"):"")+difDay+"天"; }else{ var month3 = month2-1; var res = (year2-year1)*12+(month3-month1);//月份差 var difYear = Math.floor(res/12); var difMonth = res%12; var difDayTemp = day1-day2; var dateMax3 = new Date(year2,month3,0); var dayMax3 = dateMax3.getDate(); var difDay = dayMax3-difDayTemp; return ((difYear!=0)?(difYear+"年"):"")+((difMonth!=0)?(difMonth+"个月"):"")+difDay+"天"; } } } </script> </html>

运行测试返回天数的,大家可以根据需要参考上面的代码修改即可。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdfwgj.html