Java time difference

Why is the output of Java code below - 04:18:23 and not 03:18:23?

public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); try { Date start = sdf.parse("00:44:16"); Date end = sdf.parse("04:02:39"); long duration = end.getTime() - start.getTime(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(duration); System.out.println(sdf.format(cal.getTime())); } catch (ParseException e) { e.printStackTrace(); } } 
+1
source share
3 answers

Because this is not how you get the duration. Change your code to this:

 package com.sandbox; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Sandbox { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); try { Date start = sdf.parse("00:44:16"); Date end = sdf.parse("04:02:39"); long duration = end.getTime() - start.getTime(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(duration); System.out.println(new SimpleDateFormat("yyyy MM dd HH:mm:ss").format(cal.getTime())); } catch (ParseException e) { e.printStackTrace(); } } } 

You will see that it prints 1969 12 31 19:18:23 . This date is not a duration. Since you skip the date components when you print your answer, it seems to print a duration, but it really is.

To be honest, I do not know how to do this in java. I just use the JodaTime library. There, a class called Duration makes it easier. Here is a SO question that shows how to use it to print results in any way: "pretty print" duration in java

+10
source

Alternatively, if you do not want to use JodaTime, it is quite simple to calculate hours, minutes and seconds with a duration in milliseconds:

 public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); Date start = sdf.parse("00:44:16"); Date end = sdf.parse("04:02:39"); long durationMs = end.getTime() - start.getTime(); final int oneHourMs = 3600000; final int oneMinuteMs = 60000; final int oneSecondMs = 1000; long hours = durationMs / oneHourMs; long minutes = (durationMs % oneHourMs) / oneMinuteMs; long seconds = (durationMs % oneMinuteMs) / oneSecondMs; System.out.format("%02d:%02d:%02d", hours, minutes, seconds); // outputs: 03:18:23 } 
+3
source

Problems:

  • You insert the time of day value into the date object.
  • You are using the infamous old time classes, now obsolete, superseded by the java.time classes.

The LocalTime class represents the time of day with no date and no time zone.

 LocalTime start = LocalTime.parse( "00:44:16" ); LocalTime stop = LocalTime.parse( "04:02:39" ); 

Duration is a time span that is not tied to a timeline.

 Duration duration = Duration.between ( start , stop ); 
0
source

Source: https://habr.com/ru/post/1495756/


All Articles