How to compare raw time in Java?

For example, suppose I have

String endTime = "16:30:45"; 

How can I determine if there is now until this time?

+4
source share
4 answers

First you need to analyze this:

 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss") Date date = sdf.parse(endTime); 

Then you can create a calendar to compare time:

 Calendar c = Calendar.getInstance(); c.setTime(date); Calendar now = Calendar.getInstance(); if (now.get(Calendar.HOUR_OF_DAY) > c.get(Calendar.HOUR_OF_DAY) .. etc) { .. } 

Alternatively, you can create a calendar of type now and set its fields HOUR, MINUTE and SECOND using the new calendars.

With joda-time, you can do something like this.

 new DateMidnight().withHour(..).widthMinute(..).isBefore(new DateTime()) 
+15
source
 SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); Date d1=df.parse(endTime); Date d2=df.parse(startTime); long d1Ms=d1.getTime(); long d2Ms=d2.getTime(); if(d1Ms < d2Ms) { //doSomething } else { // something else } 
+2
source

Since Java does not have native support for pure time values โ€‹โ€‹(only combined time / date values), you are probably better off implementing the comparison yourself. If the time is formatted as HH: mm: ss, this should do the trick:

 boolean beforeNow = endTime.compareTo( new SimpleDateFormat("HH:mm:ss").format(new Date())) < 0; 

The code does not handle date changes. I'm not sure if you want to treat 23:00 before or after 01:00, but the code considers both times on the same date, for example. 23:00 after 01:00.

+1
source

Local time

Before Java 8 and its java.time package, Java had no concept of "local time." This means that the time of day is disconnected from any date and in any time zone. Local time is simply an idea of โ€‹โ€‹the time of day, not tied to the timeline of history.

Both the Joda-Time library and the java.time package in Java 8 offer the LocalTime class.

Timezone

The time zone is critical for determining the local time "now." Obviously, the โ€œwall clock timeโ€ in Paris is different from what it was in Montreal at the same time.

If you omit the time zone, the current JVMs default time zone is applied. It is better to specify without referring to the current default value.

Joda time

Sample code in Joda-Time 2.7.

 LocalTime then = new LocalTime( "16:30:45" ); Boolean isNowBefore = LocalTime.now( DateTimeZone.forID( "America/Montreal" ) ).isBefore( then ); 
0
source

All Articles