user885791
user885791

Reputation: 21

Time difference between two time using java

I am trying to get time difference between two time values. (11:00:00 and 12:43:00) for above inputs it is showing correct output.

**

Time in seconds: 6180 seconds.
Time in minutes: 103 minutes.
Time in hours: 1 hours.
Time in hours Round : 2 hours.

** For Input values("11:00:00"and "2:43:00") It should give us 3 hours as round value **

Time in seconds: -29820 seconds.
Time in minutes: -497 minutes.
Time in hours: -8 hours.
Time in hours Round : -8 hours.

**

import java.lang.Math; 
import java.text.SimpleDateFormat;
import java.util.Date;


public class HelloWorld
{
  public static void main(String[] args)
  {


String dateStart = "11:00:00";
String dateStop = "12:43:00";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");  
Date d1 = null;
Date d2 = null;
try {
    d1 = format.parse(dateStart);
    d2 = format.parse(dateStop);
} catch (Exception e) {
    e.printStackTrace();
}    

// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000;         
long diffMinutes = diff / (60 * 1000);         
long diffHours = diff / (60 * 60 * 1000);              
int parkingEntry=2;
int firstHour=3;
int parkingRate=4;
int Total=0;

System.out.println("Time in seconds: " + diffSeconds + " seconds.");         
System.out.println("Time in minutes: " + diffMinutes + " minutes.");         
System.out.println("Time in hours: " + diffHours + " hours."); 

double my_hrs=diffMinutes/60d;
     int r = (int) Math.round(my_hrs);
System.out.println("Time in hours Round : " + r + " hours."); 


  }
}

Upvotes: 1

Views: 7691

Answers (2)

Anonymous
Anonymous

Reputation: 86276

Your basic problem is your input is insufficient for calculating the difference. You don’t know whether the times are before or after noon (in AM or PM). The best solution would be to require this information in the input. Either by using 24 hours (as the HH in your format already suggests) or by adding an AM/PM marker to the input.

Assuming you cannot change the input, you may of course make a best effort with what you have. If the stop time seems to be before the start time, it’s probably because the start time was AM and the stop time PM. Please note that this is far from bulletproof: It will still calculate the time from 6 to 7 as 1 hour where it might have been from 6 AM to 7 PM, that is, 13 hours, instead.

I will take this opportunity to demonstrate how to do it with the java.time classes:

    // Two formats, for AM and PM
    final String basicTimeFormatPattern = "h:mm:ss";
    DateTimeFormatter amFormat = new DateTimeFormatterBuilder().appendPattern(basicTimeFormatPattern)
            .parseDefaulting(ChronoField.AMPM_OF_DAY, 0)
            .toFormatter();
    DateTimeFormatter pmFormat = new DateTimeFormatterBuilder().appendPattern(basicTimeFormatPattern)
            .parseDefaulting(ChronoField.AMPM_OF_DAY, 1)
            .toFormatter();
    LocalTime t1 = LocalTime.parse(dateStart, amFormat);
    LocalTime t2 = LocalTime.parse(dateStop, amFormat);
    if (t2.isBefore(t1)) {
        // parse in PM instead
        t2 = LocalTime.parse(dateStop, pmFormat);
    }
    Duration diff = Duration.between(t1, t2);
    System.out.println("Time in seconds: " + diff.getSeconds() + " seconds.");         
    long diffMinutes = diff.toMinutes();
    System.out.println("Time in minutes: " + diffMinutes + " minutes.");         
    System.out.println("Time in hours: " + diff.toHours() + " hours.");

The code is about the same size as yours, but please note that the code lines are spent with the difficult part of the problem, parsing the incomplete input and determining the AM and PM, whereas trivial conversions between time units are done by library methods and don’t fill up our own code. The calculation of the rounded hours can be done as in your code in the question, so I left it out.

The above prints:

Time in seconds: 6180 seconds.
Time in minutes: 103 minutes.
Time in hours: 1 hours.
Time in hours Round : 2 hours.

Or with dateStop = "2:43:00":

Time in seconds: 13380 seconds.
Time in minutes: 223 minutes.
Time in hours: 3 hours.
Time in hours Round : 4 hours.

Upvotes: 0

Ray
Ray

Reputation: 3959

The format "HH:mm:ss" is a 24 hour format. So when you are checking the time difference between "11:00:00"and "2:43:00" you are actually checking the time difference between 11 AM and 2:43 AM.

Change your inputs to "11:00:00" and "14:43:00".

Upvotes: 1

Related Questions