Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing hours in java

First of all forgive my English :-(

I have a problem with hours on java. Let's see it by an example:

DateFormat datos = new SimpleDateFormat ("hh:mm:ss");
        Date ac, lim;
        String actual,limit;
        actual="18:01:23";
        limit="00:16:23";

        ac=datos.parse(actual);
        lim=datos.parse(limit);


        if(ac.compareTo(lim)==-1){.......

I need to solve this case in which limit is past midnight and actual hour is before midnight. My program says that actual has reached limit and it isn't correct because at the example, it has still 6 hours to finish.

I tried to solve it with DateFormat class but it doesnt see this case. I tried it with Time class too but its methods are deprecated.

How can I solve this?

like image 417
user1297810 Avatar asked Dec 10 '22 01:12

user1297810


1 Answers

Use HH instead of hh in your SimpleDateFormat:

DateFormat datos = new SimpleDateFormat("HH:mm:ss");

hh is the 12-hour clock (hours go from 1 to 12).

HH is the 24-hour clock (hours go from 0 to 23).

But besides that, there are other things wrong with this. Class Date is not very well suited to contain only a time. If you do this, it will be parsed as 01-01-1970 with the specified time. So 18:01:23 becomes 01-01-1970, 18:01:23 and 00:16:23 becomes 01-01-1970, 00:16:23. You probably wanted to compare 18:01:23 to 00:16:23 the next day.

Try something like this:

String actual = "18:01:23";
String limit = "00:16:23";

String[] parts = actual.split(":");
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
cal1.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
cal1.set(Calendar.SECOND, Integer.parseInt(parts[2]));

parts = limit.split(":");
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
cal2.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
cal2.set(Calendar.SECOND, Integer.parseInt(parts[2]));

// Add 1 day because you mean 00:16:23 the next day
cal2.add(Calendar.DATE, 1);

if (cal1.before(cal2)) {
    System.out.println("Not yet at the limit");
}

The library Joda Time is a popular Java date and time library that is much better designed than the standard Java date and calendar API; consider using it if you have to work with dates and times in Java.

With Joda Time you could do this:

String actual = "18:01:23";
String limit = "00:16:23";

DateTimeFormatter df = DateTimeFormat.forPattern("HH:mm:ss");

DateTime ac = df.parseLocalTime(actual).toDateTimeToday();
DateTime lim = df.parseLocalTime(limit).toDateTimeToday().plusDays(1);

if (ac.isBefore(lim)) {
    System.out.println("Not yet at the limit");
}
like image 124
Jesper Avatar answered Dec 29 '22 20:12

Jesper