# Difference in seconds between two times

• 09-25-2009, 09:45 PM
jazzy639
Difference in seconds between two times
Hello

Im trying to create a simple Java program that takes in two times in the format "HH MM SS" and then calculate the difference between these times in seconds.

To keep things simple, i'm just using two string values to hold the times so I can concentrate on the part of the code which does the calculation.

In other languages this would be an easy task but in Java, it seems very complicated. Can anyone help out at all?

Things to bear in mind:
Difference between 17 50 05 and 17 51 05 = 60 seconds
Difference between 17 50 05 and 17 49 05 = 60 seconds (not -60)
• 09-25-2009, 09:49 PM
StormyWaters
Convert it to seconds, calculate the difference, convert difference back.
• 09-25-2009, 10:23 PM
camickr
Quote:

To keep things simple, i'm just using two string values to hold the times
How is that simple? You can't do math on Strings.

Quote:

Difference between 17 50 05 and 17 49 05 = 60 seconds (not -60)
I'm sure you can think of a way to solve that problem
• 09-25-2009, 10:28 PM
jazzy639
This is the code I came up with, surely there is a simpler solution??

Quote:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
import java.util.Scanner;

public class AverageSpeed {

public static void main(String[] args) {

// Create Scanner to request input from user
Scanner keyboardInput = new Scanner(System.in);

// Output text to user and take a line of input as a string
System.out.println("Enter the first time: ");
String inputtime1 = keyboardInput.nextLine();

System.out.println("Enter the second time: ");
String inputtime2 = keyboardInput.nextLine();

// Need to catch errors if date format is incorrect
try {
// Define a date format the same as the expected input
SimpleDateFormat sdf = new SimpleDateFormat("HH mm ss");

// Convert the user input into a date object
Date time1 = sdf.parse(inputtime1);
Date time2 = sdf.parse(inputtime2);

// Get time values of the date objects
long l1 = time1.getTime();
long l2 = time2.getTime();
double difference = (l2 - l1)/1000; // Calculate the difference in time (divide by 1000 as in milliseconds)
difference = (difference < 0 ? -difference : difference); // If difference is negative, make positive
double mph = 1/(difference/3600); // Calculate speed
System.out.println("Average Speed: " + mph + " mph.");

} catch (ParseException e) {
e.printStackTrace();
}
}

}
• 09-25-2009, 10:51 PM
pkang
Quote:

// Get time values of the date objects
long l1 = time1.getTime();
long l2 = time2.getTime();
double difference = (l2 - l1)/1000; // Calculate the difference in time (divide by 1000 as in milliseconds)
difference = (difference < 0 ? -difference : difference); // If difference is negative, make positive
You can use double difference = (Math.abs(l2 - l1))/1000 in the red
• 09-25-2009, 10:55 PM
jazzy639
Quote:

Originally Posted by pkang
You can use double difference = (Math.abs(l2 - l1))/1000 in the red

Thanks, that works well.

Just wondering if there is a better way of doing this whole task? In other languages this would be considerably easier.
• 09-26-2009, 03:11 PM
jazzy639
bump to see if there is a better way of doing this?
• 09-26-2009, 05:02 PM
camickr
Why do you think there is a better way of doing this? Its about 4 lines of code. This would be the way it is done in other language as well. Maybe they already have a method that includes the 4 lines of code (so you don't have to write it), but any language that implements this functionality would have to follow the same basic steps.
• 09-26-2009, 05:30 PM
jazzy639
Well its not four lines, its quite long, have to import various objects and use date formats, etc.

For example, here is the same thing done in VBScript for a web application:

Quote:

time1 = CDate(Replace(Request.QueryString("time1")," ",":"))
time2 = CDate(Replace(Request.QueryString("time2")," ",":"))
mph = 1/(Abs(DateDiff("s",time1,time2))/3600)
Response.Write("Average Speed: " & mph & " mph.")
Java seems very complicated to do simple tasks.
• 09-26-2009, 05:41 PM
camickr
You could write it in one line of code in Java as well. However, most people prefer to write readable and maintainable code.

And you completely missed the point about "DateDiff" being a built in function. Each language has is own set of build in functions/methods. Java doesn't have this one, but it has others that are not in VBScript. No two languages are the same, thats why we have different languages.
• 09-26-2009, 06:17 PM
camickr
By the way your original question stated:

Quote:

so I can concentrate on the part of the code which does the calculation.
So the assumption is you where working on the the calculation and you where given the simple solution of using the Math.abs(...) method.

If your rant is about asking and accepting user input and then converting the user input to a value that can be used in the calculation then you need to learn how to ask a question properly instead of whining about the features of the language.

Using your VBScript like approach of cluttering as much code as possible on one line of code you could use:

Code:

```import java.text.*; public class ConsoleTest {         public static void main(String args[])                 throws Exception         {                 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");                 long time1 = sdf.parse( System.console().readLine("Time1 (hh:mm:ss): ") ).getTime();                 long time2 = sdf.parse( System.console().readLine("Time2 (hh:mm:ss): ") ).getTime();                 double mph = 1.0 / ( Math.abs(time1 - time2) / 3600.0 );                 System.out.println("Average Speed: " + mph + " mph");         } }```
• 09-26-2009, 06:58 PM
jazzy639
Thanks for that code, it is helpful.

By the part that does calculation, I meant ignoring getting the user to type in values, just treating two objects as time values and then getting the difference in seconds between them.