There are two times, say 17:25:28 and 20:49:12.

The difference should be 03:33:44.

How can you tell the difference between these times?

  • one
    bring in seconds, subtract, bring back. The easiest option. - pavel

2 answers 2

The difference in seconds can be obtained as follows:

DateFormat df = new java.text.SimpleDateFormat("hh:mm:ss"); Date date1 = df.parse("17:25:28"); Date date2 = df.parse("20:49:12"); //делим на тысячу, так как разность в миллисекундах long diff = (date2.getTime() - date1.getTime()) / 1000; 

Further:

 long hours = diff / 3600; long minutes = (diff - (3600 * hours)) / 60; long seconds = (diff - (3600 * hours)) - minutes * 60; System.out.println(hours + ":" + minutes + ":" + seconds); 

3:23:44

  • one
    To calculate the minutes and seconds there are shorter recordings: long minutes = (diff % 3600) / 60; , long seconds = diff % 60; . - Regent

You can use this method:

 public static String getDurationBreakdown(long millis) { if(millis < 0) { throw new IllegalArgumentException("Duration must be greater than zero!"); } long days = TimeUnit.MILLISECONDS.toDays(millis); millis -= TimeUnit.DAYS.toMillis(days); long hours = TimeUnit.MILLISECONDS.toHours(millis); millis -= TimeUnit.HOURS.toMillis(hours); long minutes = TimeUnit.MILLISECONDS.toMinutes(millis); millis -= TimeUnit.MINUTES.toMillis(minutes); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis); StringBuilder sb = new StringBuilder(64); sb.append(days); sb.append(" Days "); sb.append(hours); sb.append(" Hours "); sb.append(minutes); sb.append(" Minutes "); sb.append(seconds); sb.append(" Seconds"); return sb.toString(); } 

Example of use:

 long start = Calendar.getInstance().getTimeInMillis(); Thread.sleep(5000); long end = Calendar.getInstance().getTimeInMillis(); System.out.println(getDurationBreakdown(end - start)); 

Output to console:

 0 Days 0 Hours 0 Minutes 5 Seconds