How to calculate the number of days between two js instances-javascript tips-js tutorial

Source: Internet
Author: User
Tags date1
This article mainly introduces the example code for calculating the number of days difference between two time periods in js. If you need it, please refer to it. The Code is as follows:


// Determine whether it is a leap year
Function isLeapYear (year ){
If (year % 4 = 0 & (year % 100! = 0) | (year % 400 = 0 )))
{
Return true;
}
Return false;
}
// Judge the two dates before and after
Function validatePeriod (fyear, fmonth, fday, byear, bmonth, bday ){
If (fyear <byear ){
Return true;
} Else if (fyear = byear ){
If (fmonth <bmonth ){
Return true;
} Else if (fmonth = bmonth ){
If (fday <= bday ){
Return true;
} Else {
Return false;
}
} Else {
Return false;
}
} Else {
Return false;
}
}
// Calculate the difference between the two dates
Function dateDiff (d1, d2 ){
Var disNum = compareDate (d1, d2 );
Return disNum;
}
Function compareDate (date1, date2)
{
Var regexp =/^ (\ d {1, 4}) [-| \.] {1} (\ d {1, 2}) [-| \.] {1} (\ d {1, 2}) $ /;
Var monthDays = [,];
Regexp. test (date1 );
Var date1Year = RegExp. $1;
Var date1Month = RegExp. $2;
Var date1Day = RegExp. $3;

Regexp. test (date2 );
Var date2Year = RegExp. $1;
Var date2Month = RegExp. $2;
Var date2Day = RegExp. $3;

If (validatePeriod (date1Year, date1Month, date1Day, date2Year, date2Month, date2Day )){
FirstDate = new Date (date1Year, date1Month, date1Day );
SecondDate = new Date (date2Year, date2Month, date2Day );

Result = Math. floor (secondDate. getTime ()-firstDate. getTime ()/(1000*3600*24 ));
For (j = date1Year; j <= date2Year; j ++ ){
If (isLeapYear (j )){
MonthDays [1] = 2;
} Else {
MonthDays [1] = 3;
}
For (I = date1Month-1; I Result = result-monthDays [I];
}
}
Return result;
} Else {
Alert ('Sorry, the first time must be earlier than the second time. Thank you! ');
Exit;
}
}


Call this function to pass two time values: 2013-01-19 2013-12-19

Days = dateDiff (d1, d2 );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.