Tuesday, 15 March 2016

Time difference in Java




Why the output of the Java code below is 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();
}
}

Answer




Because that's not how you get a 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'll see it prints out 1969 12 31 19:18:23. That's a date not a duration. Since you're skipping the date components when you print out your answer, it appears like it's printing out a duration, but it's really not.



To be frank, I don't know how to do this in java. I just use the JodaTime library. There's a class called Duration that makes this easy. Here's a SO question that shows how to use it to print out the results any way you want: "pretty print" duration in java



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...