One: Calculate the number of days difference between two dates
Like what:
str1 = "2002-01-20"
str2 = "2002-10-11"
How to use JavaScript to calculate the difference between str1 and str2 days?
Copy Code code as follows:
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<title></title>
<body>
<button onclick= "Btncount_click ()" > Calculate days of Difference </button>
<script language= "JavaScript" >
function Btncount_click () {
S1 = "2002-1-10"
S2 = "2002-10-1"
Alert (DateDiff (S1,S2))
}
A function that calculates the difference in days, universal
function DateDiff (sDate1, SDate2) {//sdate1 and sDate2 are 2002-12-18 formats
var adate, oDate1, ODate2, idays
Adate = Sdate1.split ("-")
oDate1 = new Date (adate[1] + '-' + adate[2] + '-' + adate[0 ')//convert to 12-18-2002 format
Adate = Sdate2.split ("-")
ODate2 = new Date (adate[1] + '-' + adate[2] + '-' + adate[0]
Idays = parseint (Math.Abs (odate1-odate2)/1000/60/60/24)//Convert the number of milliseconds from the difference to the number of days
Return idays
}
second: Calculate the date after a certain number of days
In JavaScript, count the days after the day's date. Far from being in. NET, a function can solve the problem. On this issue, I was troubled for some time, finally through a Netizen's introduction to solve the problem. Put it together and share it.
Copy Code code as follows:
<script language= "javascript" type= "Text/javascript" >
var startdate = new Date (); var intvalue = 0;
var enddate = null;
Intvalue = Startdate.gettime (); Intvalue + + 100 * (24 * 3600 * 1000);
EndDate = new Date (intvalue);
Alert (enddate.getfullyear () + "-" + (Enddate.getmonth () +1) + "-" + enddate.getdate ());
</script>
The above 100 represents 100 days after the date that you can modify. JS in Date.gettime (), only after the date of 1970.01.01; there are 0-11 months, a little different, avoid oh. Of course, you can also calculate the date after a specific date.
Copy Code code as follows:
<script language= "javascript" type= "Text/javascript" >
var startdate = new Date (2007, (8-1), 1, 10, 10, 10);
var intvalue = 0;
var enddate = null;
Intvalue = Startdate.gettime (); Intvalue + + 100 * (24 * 3600 * 1000);
EndDate = new Date (intvalue);
Alert (enddate.getfullyear () + "-" + (Enddate.getmonth () +1) + "-" + enddate.getdate ());
</script>