1: Calculate the number of days difference between two dates
for example:
str1 = "2002-01-20"
str2 = "2002-10-11"
How to calculate the number of days between str1 and str2 using javaScript?
Copy the code code as follows:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title></title>
</head>
<body>
<button onClick="btnCount_Click()">Calculate the difference in days</button>
<script language="JavaScript">
function btnCount_Click(){
s1 = "2002-1-10"
s2 = "2002-10-1"
alert(DateDiff(s1,s2))
}
//Function to calculate the difference in days, universal
function DateDiff(sDate1, sDate2){ //sDate1 and sDate2 are in 2002-12-18 format
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 difference in milliseconds to days
return iDays
}
2: Calculate the date after a certain number of days
In JavaScript, calculate what date is several days after today's date. It is far less convenient than in .Net. A function can solve the problem. This problem troubled me for a while, and finally the problem was solved through the introduction of a netizen. Post it and share it.
Copy the 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 100 above represents the date 100 days later, which you can modify. Date.getTime() in JS can only support dates after 1970.01.01; and the month is 0 - 11, which is a bit different, so avoid it. Of course you can also calculate dates after a specific date.
Copy the 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>