1

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


  }
}
user885791
  • 21
  • 1
  • 3
  • Try using long diffInMillis = d2.getTimeInMillis() - d1.getTimeInMillis() – Fady Saad Apr 24 '17 at 06:30
  • 5
    Try using [`Duration`](https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html) and [`LocalTime`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html) – MadProgrammer Apr 24 '17 at 06:31
  • @user7790438, that won’t compile (and if it did, would not help the asker’s problem). You are confusing with the method in the `Calendar` class. The inconsistencies between the desings of `Date` and `Calendar` is just one of the things that are largely overcome when you change to `LocalTime` and `Duration` (as MadProgrammer suggested). – Ole V.V. Apr 26 '17 at 02:24
  • I suppose that for 11:00:00 and 2:43:00 you would want 4 hours as rounded value? – Ole V.V. Apr 26 '17 at 02:26

2 Answers2

1

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

Ray
  • 3,864
  • 7
  • 24
  • 36
  • Yes i can understand that, How we can covert date format for this inputs? – user885791 Apr 24 '17 at 07:03
  • http://stackoverflow.com/questions/6907968/how-to-convert-24-hr-format-time-in-to-12-hr-format, http://stackoverflow.com/questions/6531632/conversion-from-12-hours-time-to-24-hours-time-in-java. Please specify the question clearly next time. – Ray Apr 24 '17 at 07:07
  • Other options include: Add an am/pm marker to the input strings and use `hh` in the format. Or if the second time appears to be before the first, add 12 hours (again, this is easier with `LocalDate` or `Duration`). – Ole V.V. Apr 26 '17 at 02:28
0

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.
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161