For example: It is 2004-03-26 13:31:40 the past is: 2004-01-02 11:30:24 I now want to get two date difference, the form of the difference is: xx days xx hours xx minutes xx seconds
Method One: DateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
try {Date D1 = df.parse ("2004-03-26 13:31:40"); Date D2 = Df.parse ("2004-01-02 11:30:24"); Long diff = d1.gettime ()-d2.gettime (); Long days = diff/(1000 * 60 * 60 * 24); } catch (Exception e) {}
Method Two: SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Java.util.Date now = Df.parse ("2004-03-26 13:31:40"); Java.util.Date date=df.parse ("2004-01-02 11:30:24"); Long L=now.gettime ()-date.gettime (); Long day=l/(24*60*60*1000); Long hour= (l/(60*60*1000)-day*24); Long min= ((l/(60*1000))-day*24*60-hour*60); Long s= (l/1000-day*24*60*60-hour*60*60-min*60); System.out.println ("+day+" Days "+hour+" hours "+min+" minutes "+s+" seconds ");
Method Three: SimpleDateFormat dfs = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Java.util.Date begin=dfs.parse ("2004-01-02 11:30:24"); Java.util.Date end = Dfs.parse ("2004-03-26 13:31:40"); Long between= (End.gettime ()-begin.gettime ())/1000;//divided by 1000 for conversion into seconds
Long day1=between/(24*3600); Long hour1=between% (24*3600)/3600; Long minute1=between%3600/60; Long second1=between%60/60; System.out.println ("+day1+" Days "+hour1+" hours "+minute1+" minutes "+second1+" seconds ");
====================================================
Java Comparison time size
String s1= "2008-01-25 09:12:09"; String s2= "2008-01-29 09:12:11"; Java.text.DateFormat df=new Java.text.SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Java.util.Calendar c1=java.util.calendar.getinstance (); Java.util.Calendar c2=java.util.calendar.getinstance (); try {c1.settime (Df.parse (S1)); C2.settime (Df.parse (S2));} catch (Java.text.ParseException e) {System.err.println ("Malformed");} int Result=c1.compareto (C2); if (result==0) System.out.println ("C1 equal C2"); else if (result<0) System.out.println ("C1 less than C2"); Else System.out.println ("C1 greater than C2");
Java Compute time difference and compare times size (RPM)