String2date: calculate the number of days between two dates (Java)

Source: Internet
Author: User
Tags date now date1

The test is as follows:

Public long date2date (string sdate1, string sdate2) throws exception {
Simpledateformat SDF = new simpledateformat ("yyyy-mm-dd ");
Date date1 = SDF. parse (sdate1 );
Date date2 = SDF. parse (sdate2 );

Return date2.gettime ()/(24*60*60*1000)-date1.gettime ()/(24*60*60*1000 );
}

@ Test
Public void testdate2date () throws exception {
Long date = date2date ("2012-4-11", "2012-4-23 ");
System. Out. println ("difference:" + date );

}

 

 

 

It turns out that it is not a problem to calculate the date difference between the two time points until one day .... One of the developers I once coached asked me for advice. I didn't think it was very difficult. I tried to use the calendar/gregoriancalendar class for computation. It seems that the code is too complicated and I gave up. I tried for half an hour and finally came up with a sentence and wrote it to him on MSN. At that time, I felt that the road was wild and I could not go to the stage. This sentence is also a concise method to be introduced below.
Later, one of my former colleagues sent an email about the blog published on the Internet. It was interesting to have a good number of java standard libraries. The requirement is very simple: there are two date variables (a, B), how to calculate the number of days between the two? Do you have a simple solution? (According to this cool man, it is still very troublesome)
After reading Daniel's method, I secretly thought: Since the java standard library cannot be solved, isn't my method very simple ?! My confidence is soaring.

====
My method:

Public long differ (date date1, date date2)
...{
// Return date1.gettime ()/(24x60*60*1000)-date2.gettime ()/(24x60*60*1000 );
Return date2.gettime ()/86400000-date1.gettime ()/86400000; // use the immediate number to reduce the overhead of multiplication calculation
}

 

Problem Analysis: Calculate the date difference. The important part is the date part of the time object, which has nothing to do with the time, minute, and second. Therefore, the key to the problem is to filter out the hour, minute, and second, and retain the date part. The dry low-pass filter filters out high-frequency clutter and retains low-frequency signals.
Solution: the number of seconds in a day is 24*60*60*1000 = 86400000 = senconds. The time object date1.gettime () is the number of seconds since, January 1, January 1, 1970. You can use it to remove seconds and get the number of days since January 1, January 1, 1970. Note that the division symbol is used here, and the time is filtered out in seconds. Perform the same operation on date2 to get the number of days of date2. The number of days of date2 minus the number of days of date1. The result is the date difference.
For example, assume that date1 is equal to January 1, January 5, 1970, and date2 is equal to January 1, January 6, 1970. The result of date1 division by seconds is 4, the result of date2 division by seconds is 5, and the difference between date2 and date1 is 5-4 = 1 day, which is consistent with our expectation.

====
My colleague kun gave the method: Get the milliseconds subtraction of the two, and then/24/60/60.
This method should be incorrect. Because the seconds are subtracted, the time difference between the two is obtained, and the time and second are not filtered out.
Calculation Result: As shown in the preceding example, date2.gettime ()-date1.gettime () is equal to the number of seconds equivalent to 23 hours. The result is 0 days, does not match the expected 1 day.
The difference between the Kun method and the correct method is: first do subtraction, or first do division.

====
Methods found by colleagues on the Internet:

Simpledateformat myformatter = new simpledateformat ("yyyy-mm-dd ");
Java. util. Date = myformatter. parse ("2003-05-1 ");
Java. util. Date mydate = myformatter. parse ("1899-12-30 ");
Long day = (date. gettime ()-mydate. gettime ()/(24*60*60*1000 );
Out. println (day );

The result should be correct, and there is no time/second at all. The time/second method is equivalent to the Kun method. However, it may be difficult to use it, because you must obtain the date of the string before using it.

====
Finally, let's take a look at Daniel's methods:
Daniel blog address: http://blog.csdn.net/rmartin/archive/2006/12/22/1452867.aspx

Private int daysbetween (date now, date returndate )...{
Calendar cnow = calendar. getinstance ();
Calendar creturndate = calendar. getinstance ();
Cnow. settime (now );
Creturndate. settime (returndate );
Settimetomidnight (cnow );
Settimetomidnight (creturndate );
Long todayms = cnow. gettimeinmillis ();
Long returnms = creturndate. gettimeinmillis ();
Long intervalms = todayms-returnms;
Return millisecondstodays (intervalms );
}

Private int millisecondstodays (long intervalms )...{
Return (INT) (intervalms/(1000*86400 ));
}

Private void settimetomidnight (calendar )...{
Calendar. Set (calendar. hour_of_day, 0 );
Calendar. Set (calendar. Minute, 0 );
Calendar. Set (calendar. Second, 0 );
}

 

It looks complicated. I have never verified it. It should be correct!

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.