JS JavaScript计算两日期之间的相差天数
1、直接上代码:function daysBetween(DateOne,DateTwo){ var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('/')); var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('/')+1); var OneYear = DateOne.substring(0,DateOne.indexOf ('/')); var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('/')); var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('/')+1); var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('/')); var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(TwoMonth+'/'+TwoDay+'/'+TwoYear))/86400000)+1; return Math.abs(cha); }
2、用法
3、效果
4、方法已经封装好可以直接使用下面HTML代码
5、<!DOCTYPE html><html><head> <title></title></head><body><button onclick="fun()">测试</button><script type="text/javascript">function fun(){alert(daysBetween('2017/07/10','2017/07/18'))//id)}/*daysBetween(DateOne,DateTwo)*计算两日期之间的相差天数*日期格式 yyyy/mm/dd*两个参数*/function daysBetween(DateOne,DateTwo){ var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('/')); var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('/')+1); var OneYear = DateOne.substring(0,DateOne.indexOf ('/')); var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('/')); var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('/')+1); var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('/')); var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(TwoMonth+'/'+TwoDay+'/'+TwoYear))/86400000)+1; return Math.abs(cha); } </script></body></html>
6、注意事项日期格式 yyyy/mm/dd
7、返回结果不包括来时两天