JS date plus or minus date arithmetic code

  • 2020-10-07 18:33:58
  • OfStack

1. The date minus the number of days equals the second date


function cc(dd,dadd){
// You can add error handling 
var a = new Date(dd)
a = a.valueOf()
a = a - dadd * 24 * 60 * 60 * 1000
a = new Date(a)
alert(a.getFullYear() + " years " + (a.getMonth() + 1) + " month " + a.getDate() + " day ")
}
cc("12/23/2002",2)

It has to be supplemented here, wasting a lot of time to draw a lesson:
Javascript for time
The Numbers 0-11 indicate the months from January to December: var a= new Date(2006,5,6) results in a 2006-6-6
0-6 is the week
1-31 is the date
0-23 hours
0-59 minutes, seconds

2. // The difference between the two dates (d1-d2).


function DateDiff(d1,d2){
  var day = 24 * 60 * 60 *1000;
try{  
    var dateArr = d1.split("-");
  var checkDate = new Date();
    checkDate.setFullYear(dateArr[0], dateArr[1]-1, dateArr[2]);
  var checkTime = checkDate.getTime();
 
  var dateArr2 = d2.split("-");
  var checkDate2 = new Date();
    checkDate2.setFullYear(dateArr2[0], dateArr2[1]-1, dateArr2[2]);
  var checkTime2 = checkDate2.getTime();
  
  var cha = (checkTime - checkTime2)/day; 
    return cha;
  }catch(e){
  return false;
}
}//end fun

3. Application:


<script language="javascript" type="text/javascript">
var flag = Array();// The global variable 

var start = "2009-01-01";
var end = "2009-02-24";
SetFlag(start,end); 

for(var i=0; i<flag.length; i++){
  document.write(flag[i]+"\n\r");
}

// Set the date within the period ( An array of )
function SetFlag(start,end){
var cdate = Array();
cdate = start.split("-");
var cd = cdate[1]+"/"+cdate[2]+"/"+cdate[0]; 
var dayNum = DateDiff(end,start);
for(var i=0; i<=dayNum; i++){
  flag.push(AddDays(cd,i));
}
}//end fun
// The date plus the new date after the number of days .
function AddDays(date,days){
var nd = new Date(date);
  nd = nd.valueOf();
  nd = nd + days * 24 * 60 * 60 * 1000;
  nd = new Date(nd);
  //alert(nd.getFullYear() + " years " + (nd.getMonth() + 1) + " month " + nd.getDate() + " day ");
var y = nd.getFullYear();
var m = nd.getMonth()+1;
var d = nd.getDate();
if(m <= 9) m = "0"+m;
if(d <= 9) d = "0"+d; 
var cdate = y+"-"+m+"-"+d;
return cdate;
}
// The difference between the two dates (d1 - d2).
function DateDiff(d1,d2){
  var day = 24 * 60 * 60 *1000;
try{  
    var dateArr = d1.split("-");
  var checkDate = new Date();
    checkDate.setFullYear(dateArr[0], dateArr[1]-1, dateArr[2]);
  var checkTime = checkDate.getTime();
 
  var dateArr2 = d2.split("-");
  var checkDate2 = new Date();
    checkDate2.setFullYear(dateArr2[0], dateArr2[1]-1, dateArr2[2]);
  var checkTime2 = checkDate2.getTime();
  
  var cha = (checkTime - checkTime2)/day; 
    return cha;
  }catch(e){
  return false;
}
}//end fun
</script>

Related articles: