0

I'm working on a Java program where the user, at some point, give us as an input two times (in format String). We can assume the times are from the same day. For example in the console:

Please introduce time 1:
16:00

Please introduce time 2:
10:00

My program will capture those two time values as a String and my idea was to parse it into an object of class Date.

How could I calculate which time goes first in the course of a day?

For the previous example, I would like to print the first time that takes place on the day.

How can I properly do the following?

if (date1 <= date2) System.out.println(date1);   //Suppose date1 and date2 are Date objects
else System.out.println(date2);
user157629
  • 624
  • 4
  • 17
  • 3
    This is a very general question, you would be best advised to forget the Date (And Calendar) classes and instead read a [tutorial on the new java time classes](https://docs.oracle.com/javase/tutorial/datetime/index.html) – OH GOD SPIDERS Apr 21 '20 at 08:40

1 Answers1

3
String firstDateString = "16:00";
String secondDateString = "10:00";

LocalTime firstLocalTime = LocalTime.parse(firstDateString, DateTimeFormatter.ofPattern("HH:mm"));
LocalTime secondLocalTime = LocalTime.parse(secondDateString, DateTimeFormatter.ofPattern("HH:mm"));

if (firstLocalTime.isAfter(secondLocalTime)) {
  System.out.println(secondLocalTime);
} else {
  System.out.println(firstLocalTime);
}
Emile Pels
  • 3,837
  • 1
  • 15
  • 23