Summary of the days for calculating the difference between two dates in JAVA

Source: Internet
Author: User
Tags current time date1 string format

When developing logistics or other functions in Java, the data with different dates may be used for multiple days.

Call method:

The code is as follows: Copy code

Long date1 = getDateTime ("20121201"); // you can change it to your own date type, but in the format of "20121212"
Long date2 = getdatetime( "20121212 ");
Int day = dateInterval (date1, date2 );
System. out. println (day );

Call the specific implementation method:

The code is as follows: Copy code

/**
* Calculates the number of days for the difference between two dates.
* It is recommended that the value of date1 be greater than the value calculated by date2 as a positive number.
* @ Param date1 date 1
* @ Param date2 date 2
* @ Return date1-date2
*/
Public static int dateInterval (long date1, long date2 ){
If (date2> date1 ){
Date2 = date2 + date1;
Date1 = date2-date1;
Date2 = date2-date1;
    }
 
// The Canlendar class is an abstract class
// Provides rich calendar fields
// Used in this program
// YEAR in the Calendar. YEAR date
// Calendar. DAY_OF_YEAR number of days in the current year
// GetActualMaximum (Calendar. DAY_OF_YEAR) returns the 365 or 366 days of this year.
Calendar calendar1 = Calendar. getInstance (); // Obtain a Calendar
Calendar1.setTimeInMillis (date1); // use the given long value to set the current time value of the Calendar.
       
Calendar calendar2 = Calendar. getInstance ();
Calendar2.setTimeInMillis (date2 );
// First determine whether the same year
Int y1 = calendar1.get (Calendar. YEAR );
Int y2 = calendar2.get (Calendar. YEAR );
       
Int d1 = calendar1.get (Calendar. DAY_OF_YEAR );
Int d2 = calendar2.get (Calendar. DAY_OF_YEAR );
Int maxDays = 0;
Int day = 0;
If (y1-y2> 0 ){
Day = numerical (maxDays, d1, d2, y1, y2, calendar2 );
} Else {
Day = d1-d2;
    }
Return day;
}  
   
/**
* Date interval calculation
* Formula (example ):
* 20121201-20121212
* Retrieve 20121201 the number of days that have passed the year, d1 = days, and 20121212 the number of days that have passed the year, d2 = days.
* If there are 366 days in the year of January 1, the number of days in the interval will + 1, because there will be 29 days in August.
* @ Param maxDays is used to record 365 days or 366 days in a year.
* @ Param d1 indicates the number of days passed in the year.
* @ Param d2 indicates the number of days passed in the year.
* @ Param y1: currently, July 22, 2012
* @ Param y2: Currently July 22, 2012
* @ Param calendar obtain the number of days in a year based on the calendar object.
* @ Return calculates the number of days after the date interval.
*/
Public static int numerical (int maxDays, int d1, int d2, int y1, int y2, Calendar calendar ){
Int day = d1-d2;
Int betweenYears = y1-y2;
List <Integer> d366 = new ArrayList <Integer> ();
       
If (calendar. getActualMaximum (Calendar. DAY_OF_YEAR) = 366 ){
System. out. println (calendar. getActualMaximum (Calendar. DAY_OF_YEAR ));
Day + = 1;
    }
       
For (int I = 0; I <betweenYears; I ++ ){
// Set the number of days in the next year in the year + 1
Calendar. set (Calendar. YEAR, (calendar. get (Calendar. YEAR) + 1 );
MaxDays = calendar. getActualMaximum (Calendar. DAY_OF_YEAR );
// You do not need to add more 366 records in the first 366 days. Do not add the records first and then add less Records.
If (maxDays! = 366 ){
Day + = maxDays;
} Else {
D366.add (maxDays );
        }
// If the last maxDays equals 366 day-1
If (I = betweenYears-1 & betweenYears> 1 & maxDays = 366 ){
Day-= 1;
        }
    }
       
For (int I = 0; I <d366.size (); I ++ ){
// One or more 366 days
If (d366.size ()> = 1 ){
Day + = d366.get (I );
        } 
    }  
Return day;
}
   
/**
* Replace the date string with the date
* @ Param strDate: yyyyMMdd
* @ Return the number of milliseconds of the February date
*/
Public static long getDateTime (String strDate ){
Return getDateByFormat (strDate, "yyyyMMdd"). getTime ();
}
   
/**
* @ Param strDate date string
* @ Param format: Date format
* @ Return Date
*/
Public static Date getDateByFormat (String strDate, String format ){
SimpleDateFormat sdf = new SimpleDateFormat (format );
Try {
Return (sdf. parse (strDate ));
} Catch (Exception e ){
Return null;
    }
}

Example 2

The code is as follows: Copy code

Import java. text. ParseException;
Import java. text. SimpleDateFormat;
Import java. util. Calendar;
Import java. util. Date;


Public class test16 {

/**
* @ Param args
* @ Throws ParseException
*/
Public static void main (String [] args) throws ParseException {
// TODO Auto-generated method stub
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");
Date d1 = sdf. parse ("10:10:10 ");
Date d2 = sdf. parse ("00:00:00 ");
System. out. println (daysBetween (d1, d2 ));

System. out. println (daysBetween ("10:10:10", "00:00:00 "));
 }
 
/**
* Calculate the number of days between two dates
* @ Param smdate a small time
* @ Param bdate a large time
* @ Return days of difference
* @ Throws ParseException
*/
Public static int daysBetween (Date smdate, Date bdate) throws ParseException
    { 
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd ");
Smdate = sdf. parse (sdf. format (smdate ));
Bdate = sdf. parse (sdf. format (bdate ));
Calendar cal = Calendar. getInstance ();
Cal. setTime (smdate );
Long time1 = cal. getTimeInMillis ();
Cal. setTime (bdate );
Long time2 = cal. getTimeInMillis ();
Long between_days = (time2-time1)/(1000*3600*24 );
         
Return Integer. parseInt (String. valueOf (between_days ));
    } 
   
/**
* String date format calculation
*/
Public static int daysBetween (String smdate, String bdate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd ");
Calendar cal = Calendar. getInstance ();
Cal. setTime (sdf. parse (smdate ));
Long time1 = cal. getTimeInMillis ();
Cal. setTime (sdf. parse (bdate ));
Long time2 = cal. getTimeInMillis ();
Long between_days = (time2-time1)/(1000*3600*24 );
         
Return Integer. parseInt (String. valueOf (between_days ));
    }

}

Example 3

The code is as follows: Copy code

// Obtain the remaining days
SimpleDateFormat df = new SimpleDateFormat ("yyyymmdd ");
Date d0 = new java. util. Date ();
Date d1 = df. parse (end_date );
Long time0 = d0.getTime ();
Long time1 = d1.getTime ();
System. out. println (time1-time0)/(1000*60*60*24 ));

In this way, it is better to calculate the number of days with two time differences.

The code is as follows: Copy code
/**
* Calculate the number of days between two dates
     *
* @ Param date1
* @ Param date2
* @ Return
*/
Public static int diffdates (Date date1, Date date2 ){
Int result = 0;
ElapsedTime et = new ElapsedTime ();
GregorianCalendar gc1 = new GregorianCalendar ();
GregorianCalendar gc2 = new GregorianCalendar ();
Gc1.setTime (date1 );
Gc2.setTime (date2 );
Result = et. getDays (gc1, gc2 );
Return result;
    }

The method in ElapseTime is:

The code is as follows: Copy code

Public int getDays (GregorianCalendar g1, GregorianCalendar g2 ){
Int elapsed = 0;
GregorianCalendar gc1, gc2;
If (g2.after (g1 )){
Gc2 = (GregorianCalendar) g2.clone ();
Gc1 = (GregorianCalendar) g1.clone ();
} Else {
Gc2 = (GregorianCalendar) g1.clone ();
Gc1 = (GregorianCalendar) g2.clone ();
  }
Gc1.clear (Calendar. MILLISECOND );
Gc1.clear (Calendar. SECOND );
Gc1.clear (Calendar. MINUTE );
Gc1.clear (Calendar. HOUR_OF_DAY );
Gc2.clear (Calendar. MILLISECOND );
Gc2.clear (Calendar. SECOND );
Gc2.clear (Calendar. MINUTE );
Gc2.clear (Calendar. HOUR_OF_DAY );
While (gc1.before (gc2 )){
Gc1.add (Calendar. DATE, 1 );
Elapsed ++;
  }
Return elapsed;
}

In fact, joda is the simplest

The code is as follows: Copy code

Public boolean isRentalOverdue (DateTime datetimeRented ){
Period export alperiod = Period. days (2 );
Return datetimeRented. plus (financialperiod). isBeforeNow ()
}

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.