# Thread: Difference in seconds between two times

1. Member Join Date
Sep 2009
Posts
7
Rep Power
0

## 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)  Reply With Quote

2. Senior Member Join Date
Feb 2009
Posts
312
Rep Power
11

## Convert it to seconds, calculate the difference, convert difference back.  Reply With Quote

3. Senior Member Join Date
Jul 2009
Posts
1,236
Rep Power
12

## 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.

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  Reply With Quote

4. Member Join Date
Sep 2009
Posts
7
Rep Power
0

## This is the code I came up with, surely there is a simpler solution??

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();
}
}

}  Reply With Quote

5. Member Join Date
Sep 2009
Posts
6
Rep Power
0

## // 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  Reply With Quote

6. Member Join Date
Sep 2009
Posts
7
Rep Power
0

##  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.  Reply With Quote

7. Member Join Date
Sep 2009
Posts
7
Rep Power
0

## bump to see if there is a better way of doing this?  Reply With Quote

8. Senior Member Join Date
Jul 2009
Posts
1,236
Rep Power
12

## 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.  Reply With Quote

9. Member Join Date
Sep 2009
Posts
7
Rep Power
0

## 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:

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.  Reply With Quote

10. Senior Member Join Date
Jul 2009
Posts
1,236
Rep Power
12

## 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.  Reply With Quote

11. Senior Member Join Date
Jul 2009
Posts
1,236
Rep Power
12

## By the way your original question stated:

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:

Java 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");
}
}```  Reply With Quote

12. Member Join Date
Sep 2009
Posts
7
Rep Power
0

## 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.

Didnt know about the System.console().readLine so thanks!  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•