I am trying to calculate the time difference in java by input time format in 12 hours it works well when i input start time 11:58:10 pm
and end time 12:02:15 am
. But as i enter 12:00:00 am and 12:00:00 pm it give difference 0 minutes. don't know why. Below is my code please let me know where i am wrong.
Scanner input = new Scanner(System.in);
System.out.print("Enter start time (HH:mm:ss aa): ");
String starttime = input.nextLine();
System.out.print("Enter end time (HH:mm:ss aa): ");
String endtime = input.nextLine();
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss aa");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(starttime);
d2 = format.parse(endtime);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
System.out.print(diffMinutes + " minutes and "+diffSeconds + " seconds.");
} catch (Exception e) {
System.out.println("Invalid fromat");
}
The new java.time
methods LocalTime
, DateTimeFormatter
and Duration
provide much better methods for handling this. For example:
DateTimeFormatter format = DateTimeFormatter.ofPattern("h:m:s a");
LocalTime time1 = LocalTime.parse("12:00:00 am", format);
LocalTime time2 = LocalTime.parse("2:00:20 pm", format);
Duration dur = Duration.between(time1, time2);
System.out.println(dur.toMinutes() + " minutes " + dur.toSecondsPart() + " seconds");
Note: Duration.toSecondsPart
requires Java 9 or later, the rest of this code requires Java 8 or later.