Time difference calculation

Now it is: 2004-03-26 13:31:40

Past: 2004-01-02 11:30:24

I now want to get the difference between two dates, in the form of the difference is: XX days XX XX hours XX minutes seconds

This time around may be machine generated, or it may be manually entered, then we can be done by following the code

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 (); // this is a difference obtained microsecond

  long days = diff / (1000 * 60 * 60 * 24);

 

  long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);

  long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);

  System.out.println(""+days+"天"+hours+"小时"+minutes+"分");

 

}

catch (Exception e)

{

}

Guess you like

Origin www.cnblogs.com/sunjian43792901/p/11130743.html