封装两个小功能,简单易懂好操作;涉及到日期的功能避免不了会计算日期的;今天分享给大家;
1、js计算两个日期相差几天;
function DateDiff(sDate1, sDate2){ //sDate1和sDate2是2006-12-18格式 var aDate1, aDate2, oDate1, oDate2, iDays; aDate1 = sDate1.split("-"); oDate1 = new Date(aDate1[1] + '/' + aDate1[2] + '/' + aDate1[0]); aDate2 = sDate2.split("-"); oDate2 = new Date(aDate2[1] + '/' + aDate2[2] + '/' + aDate2[0]); iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24 ); return iDays } var date1 = "2018-12-07",date2 = "2018-12-19"; var n = DateDiff(date1,date2); console.log(n);//结果:12
2、js计算几天后或几天前是什么日期;
function dates(index){ var that = this; var d = new Date(NuDate); var yyyy,mm,dd; d.setDate(d.getDate() + index); yyyy = d.getFullYear(); d.getMonth()+1 < 10?mm = "0"+(d.getMonth()+1):mm = d.getMonth()+1; d.getDate() < 10?dd = "0"+d.getDate():dd = d.getDate(); return yyyy+"-"+mm+"-"+dd; }; var nu = 2;//值为正结果为日期往后几天,值为负结果为日期前几天; var NuDate = "2018-12-05";//2018-12-05 12:00:00带不带时间都可以 var nus = dates(nu); console.log(nus)//结果2018-12-07