开发者

How do I compare a raw time in Java?

开发者 https://www.devze.com 2023-03-06 17:26 出处:网络
For example suppose I have String endTime = \"16:30:45\"; How would I determine whether right now is before this time开发者_开发技巧?First, you need to parse this:

For example suppose I have

String endTime = "16:30:45";

How would I determine whether right now is before this time开发者_开发技巧?


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())


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
}


Since Java has no builtin support for pure time values (just combined time/date values), you're 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 am not sure if you want to treat 23:00 to be before or after 01:00, but the code consider both times to be on the same date, e.g. 23:00 is after 01:00.


Local Time

Before Java 8 and its java.time package, Java lacked any concept of "local time". That means a time-of-day detached from any date and fro any time zone. A local time is just the idea of a time of day without being tied to the time line of history.

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

Time Zone

Time zone is crucial for determining the local time of "now". Obviously the "wall clock time" in Paris is different than in Montréal at the same moment.

If you omit the time zone, your JVM’s current default time zone is applied. Better to specify than rely implicitly on current default.

Joda-Time

Example code in Joda-Time 2.7.

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

精彩评论

暂无评论...
验证码 换一张
取 消