Reprint please indicate the source. Thanks, http://blog.csdn.net/harryweasley/article/details/42121485.
When thinking about calculating the difference. We're definitely thinking about "2014.12.14"-"2014.12.20" = 4, this scenario, but Java doesn't give us the solution, so I'm thinking of converting the string to the date type and then
Date is converted to the calendar type, and this method is addressed through the Calendar.add () method.
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 {S Tring 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;//instantiation Calendarcalendar cal Endar = new GregorianCalendar (); Calendar calendar2 = Calendar.getinstance ();//parse string to date type SimpleDateFormat SDF = new by SimpleDateFormat 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));//Put date type into Calendarcalendar.settime (Sdf.parse (firsttime)) ; Calendar2.settime (Sdf.parse (Secondtime)); while (Calendar.compareto (CALENDAR2) > 0) {date in//calendar type + 1calendar2.add (calendar.date, 1);d ay++;} Return Day;}}
The output result is
First time Wed Dec 00:00:00 CST 2014 second time Sat Dec 00:00:00 CST 20144
Attention:
SimpleDateFormat SDF = new SimpleDateFormat ("yyyy. Mm.dd ");
Sdf.parse (firsttime) I need to talk about this here. Converted strings and SimpleDateFormat must be exactly the same, I just made a mistake. Will simpledateformat SDF = new SimpleDateFormat ("Yyyy-mm-dd"); write it like this, it will throw an exception.
The code has been staring and should be able to see clearly.
For a date-related class of Java, you can click here http://blog.csdn.net/harryweasley/article/details/41977633
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Java gets the difference between dates