Get the difference of date in java, java get the difference of date
Reprinted please indicate the source, thank you http://blog.csdn.net/harryweasley/article/details/42121485
When we want to calculate the difference value, we must think of "2014.12.14"-"2014.12.20" = 4. This method, but java does not directly give us this method, so what I want is to convert the string to the Date type, and then convert
Date is converted to the Calendar type. You can use the Calendar. add () method to solve this problem.
Package lgx. java. test; import java. text. parseException; import java. text. simpleDateFormat; import java. util. calendar; import java. util. gregorianCalendar; public class DataDemo {public static void main (String [] args) throws ParseException {String firstTime = "2014.12.24"; String secondTime = "2014.12.20"; System. out. println (getDay (firstTime, secondTime);} private static int getDay (String firstTime, String secondTime) throws ParseException {int day = 0; // instantiate CalendarCalendar calendar = new GregorianCalendar (); Calendar calendar2 = Calendar. getInstance (); // parses the string to Date type SimpleDateFormat sdf = new SimpleDateFormat ("yyyy. MM. dd "); sdf. parse (firstTime); sdf. parse (secondTime); System. out. println ("\ n first time" + sdf. parse (firstTime); System. out. println ("\ n Second Time" + sdf. parse (secondTime); // Add the Date type to the Calendarcalendar. setTime (sdf. parse (firstTime); calendar2.setTime (sdf. parse (secondTime); while (calendar. compareTo (calendar2)> 0) {// Date + 1calendar2 in the Calendar type. add (Calendar. DATE, 1); day ++;} return day ;}}
The output result is
First time Wed Dec 24 00:00:00 CST 2014 second time Sat Dec 20 00:00:00 CST 20144
Note:
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy. MM. dd ");
Sdf. parse (firstTime) here I have to say that the converted string and simpleDateFormat must be exactly the same. I just made a mistake, write SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd"); in this way, an exception is thrown.
The Code has been annotated and should be clear.
For java date-related classes, you can click here http://blog.csdn.net/harryweasley/article/details/41977633