Results 1 to 12 of 12
  1. #1
    jazzy639 is offline Member
    Join Date
    Sep 2009
    Posts
    7
    Rep Power
    0

    Default 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)

  2. #2
    StormyWaters is offline Senior Member
    Join Date
    Feb 2009
    Posts
    305
    Rep Power
    6

    Default

    Convert it to seconds, calculate the difference, convert difference back.

  3. #3
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    7

    Default

    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

  4. #4
    jazzy639 is offline Member
    Join Date
    Sep 2009
    Posts
    7
    Rep Power
    0

    Default

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

    }

  5. #5
    pkang is offline Member
    Join Date
    Sep 2009
    Posts
    6
    Rep Power
    0

    Default

    // 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

  6. #6
    jazzy639 is offline Member
    Join Date
    Sep 2009
    Posts
    7
    Rep Power
    0

    Default

    Quote Originally Posted by pkang View Post
    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.

  7. #7
    jazzy639 is offline Member
    Join Date
    Sep 2009
    Posts
    7
    Rep Power
    0

    Default

    bump to see if there is a better way of doing this?

  8. #8
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    7

    Default

    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.

  9. #9
    jazzy639 is offline Member
    Join Date
    Sep 2009
    Posts
    7
    Rep Power
    0

    Default

    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.

  10. #10
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    7

    Default

    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.

  11. #11
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    7

    Default

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

  12. #12
    jazzy639 is offline Member
    Join Date
    Sep 2009
    Posts
    7
    Rep Power
    0

    Default

    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!

Similar Threads

  1. getting time elapsed in seconds
    By ali_sakar in forum New To Java
    Replies: 3
    Last Post: 03-06-2009, 08:37 AM
  2. Need help with calculate the number of seconds
    By ProUnbeatable in forum New To Java
    Replies: 5
    Last Post: 10-11-2008, 03:07 AM
  3. Replies: 1
    Last Post: 06-30-2008, 07:14 AM
  4. Replies: 0
    Last Post: 06-26-2008, 07:32 PM
  5. measuring time in nano seconds
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-06-2007, 12:11 PM

Posting Permissions

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