游戏10代
2019-11-28 09:27:01浏览 6449
//获取时间差
function dayCha(startime,endime){
startime = startime.replace(new RegExp("-","gm"),"/");//转换-变为/
var start = new Date(startime);
var startYear = start.getFullYear(); //开始年份
var startMonth = start.getMonth() + 1;//开始月份
var startDay = start.getDate(); //开始日期
var startMiao = start.getTime();
endime = endime.replace(new RegExp("-","gm"),"/");
var end = new Date(endime);
var endYear = end.getFullYear(); //结束年份
var endMonth = end.getMonth() + 1;//结束月份
var endDay = end.getDate(); //结束日期
var endMiao = end.getTime();
var years = 0;
var months = endMonth - startMonth + (endYear - startYear) * 12;//总月
if (endMonth * 100 + endDay < startMonth * 100 + startDay) {
months--;//如果结束日期<输入日期,月数要-1
}
years = Math.floor(months / 12);//取整计算年数
months = months % 12;//取余计算月数
var middleDate = new Date(startime);//中间时间
middleDate.setFullYear(startYear + years);//设置中间时间年份
middleDate.setMonth(start.getMonth() + months);//设置中间时间月份
var days = Math.floor( ( endMiao- middleDate.getTime()) / 24 / 60/ 60 / 1000);//计算天数
//时间差的毫秒数
var chaTime=endMiao-startMiao;
//计算出小时数
var yu=chaTime % (24*3600*1000);//86400000
var hour=Math.floor(yu/(3600*1000));//3600000
//计算相差分钟数
var yuH=chaTime % (3600*1000);
var min=Math.floor(yuH/(60*1000));//60000
//计算相差秒数
var yuM=chaTime%(60*1000);
var sec=Math.floor(yuM/1000);//1000
var chastr = years+'年/'+months+'月/'+days+'天 '+hour+'时:'+min+'分:'+sec+'秒';
console.log('相差时间:'+chastr);
return {year:years,month:months,day:days,hour:hour,minute:min,second:sec};
}