Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare a raw time in Java?

Tags:

java

time

For example suppose I have

String endTime = "16:30:45";

How would I determine whether right now is before this time?

like image 255
deltanovember Avatar asked Dec 03 '22 02:12

deltanovember


2 Answers

First, you need to parse this:

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

Then you can create use a calendar to compare the 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 like now and set its HOUR, MINUTE and SECOND fields with the ones from the new calendar.

With joda-time you can do something similar.

new DateMidnight().withHour(..).widthMinute(..).isBefore(new DateTime())
like image 65
Bozho Avatar answered Dec 28 '22 01:12

Bozho


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
}
like image 29
midhunhk Avatar answered Dec 28 '22 01:12

midhunhk