Java calculates an instance of two date difference _java

Source: Internet
Author: User
Tags date1 string format

In the Java development of logistics or other functions will be used to two date different days of data, so tidy up a spare.
Call Mode:

Copy Code code as follows:

Long date1 = GetDateTime ("20121201")//can be changed to its own date type, but in "20121212" format
Long date2 = GetDateTime ("20121212");
int day = DateInterval (date1, date2);
System.out.println (day);

Specific implementation method calls:
Copy Code code as follows:

/**
* Calculate the number of days between two dates
* Recommended date1 is greater than date2 the value of this calculation is positive
* @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;
}

Canlendar The class is an abstract class
Provides a rich calendar field
This program is used in the
Year in Calendar.year date
Calendar.day_of_year days in the current year
Getactualmaximum (Calendar.day_of_year) return this year is 365 days or 366 days
Calendar calendar1 = Calendar.getinstance (); Get a calendar
Calendar1.settimeinmillis (date1); Sets the current time value for this Calendar with the given long value.

Calendar calendar2 = Calendar.getinstance ();
Calendar2.settimeinmillis (DATE2);
Judge first 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
* Calculation formula (sample):
* 20121201-20121212
* Take out 20121201 How many days have passed in this year D1 = days out 20121212 How many days have passed in this year D2 = Days
* If there are 366 days in 2012 this year, the interval will be +1, since February is 29th.
* @param maxdays is used to record 365 days or 366 days in a year
* @param d1 say how many days have passed in the year
* @param D2 say how many days have passed in the year
* @param Y1 is currently 2012 years old
* @param Y2 is currently 2012 years old
* @param calendar Gets the number of days in a year based on the Calendars object
* @return count 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++) {
Year + 1 set how many days in the next year
Calendar.set (Calendar.year, (Calendar.get (calendar.year)) + 1);
Maxdays = Calendar.getactualmaximum (calendar.day_of_year);
The first 366 days without + 1 will be all 366 records, first do not add and then one less
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 of the 366 days
if (D366.size () >= 1) {
Day + + d366.get (i);
}
}
Return day;
}

/**
* Convert date string to date
* @param strdate Date Support Month Day example: YYYYMMDD
* @return The number of milliseconds for the date of January 1, 1970
*/
public static long GetDateTime (String strdate) {
Return Getdatebyformat (strdate, "YyyyMMdd"). GetTime ();
}

/**
* @param strdate Date string
* @param format Date
* @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
Copy Code code as follows:

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 ("2012-09-08 10:10:10");
Date d2=sdf.parse ("2012-09-15 00:00:00");
System.out.println (Daysbetween (D1,D2));
System.out.println (Daysbetween ("2012-09-08 10:10:10", "2012-09-15 00:00:00"));
}

/**
* Calculate the number of days between two dates
* @param smdate smaller time
* @param bdate larger time
* @return Difference days
* @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));
}

/**
* Calculation of date format of the string
*/
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
Copy Code code as follows:

Get 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));

This is a two-time difference in the number of days is better
Copy Code code as follows:

/**
* 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;
}

Then the method in Elapsetime is:
Copy Code code as follows:

public int getdays (GregorianCalendar g1, GregorianCalendar G2) {
  I NT 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, the simplest use of Joda
Copy Code code as follows:

public boolean isrentaloverdue (DateTime datetimerented) {
Period rentalperiod = period.days (2);
Return Datetimerented.plus (Rentalperiod). 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.