Common Java Date Method collection (Part Two)

Source: Internet
Author: User

6.Java date computes the number of interval days between two arbitrary times (this comparison is common):

(1) The Calendar object is passed in:

public int getintervaldays (Calendar startday,calendar endday) ... {
if (Startday.after (endday)) ...  {
Calendar cal=startday;  
Startday=endday;  
endday=cal;    
}
Long Sl=startday.gettimeinmillis ();  
long El=endday.gettimeinmillis ();             
long EI=EL-SL;  return
(int) (ei/(1000*60*60*24));
}     

(2) The Date object is passed in:

public int getintervaldays (Date startday,date endday) ... {
if (Startday.after (endday)) ...  {
Date cal=startday;  
Startday=endday;  
endday=cal;    
}
Long Sl=startday.gettime ();         
long El=endday.gettime ();             
long EI=EL-SL;  return
(int) (ei/(1000*60*60*24));
}

(3) Improve the precise calculation of the number of days apart:

public int Getdaysbetween (Calendar d1, calendar D2) ... {
if (D1.after (D2)) ...  {
Java.util.Calendar swap = D1;  
D1 = d2;  
d2 = swap;    
}
int days = D2.get (calendar.day_of_year)-D1.get (calendar.day_of_year);  
int y2 = d2.get (calendar.year);
if (D1.get (calendar.year)!= y2) ...  {
D1 = (Calendar) d1.clone (); Do
... {
days = D1.getactualmaximum (calendar.day_of_year);//Get the actual day of the year
D1.add (Calendar .  year, 1);  While
(D1.get (calendar.year)!= y2);    
}
return days;
}

Note: The above method can be derived to ask for any time, such as to find out the mailbox within three weeks of mail received (get the current system time-and then get three weeks ago) with the time of the collection to match the best fitted into a long to compare.

such as: 1 years ago Date (note milliseconds conversion):

Java.util.Date mydate=new java.util.Date ();  
Long Mytime= (Mydate.gettime ()/1000) -60*60*24*365;  
Mydate.settime (mytime*1000);
String Mdate=formatter.format (mydate);

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.