Comparison of clocks in java
First of all, excuse my english: --(
I have a problem with a clock in java. Let's look at 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 where the limit is past midnight and the actual hour is before midnight. My program says the actual has reached the limit and this is incorrect because in this example it has 6 more hours.
I tried to solve it with DateFormat class, but it doesn't see this case. I tried it too using the Time class, but its methods are deprecated.
How can I solve this?
source to share
Use HH
instead HH
in SimpleDateFormat
:
DateFormat datos = new SimpleDateFormat("HH:mm:ss");
HH
- this is 12-hour time (hours go from 1 to 12).
HH
- this is a 24-hour mode (hours go from 0 to 23).
But there are other things in this as well. The class is Date
not well suited to contain only 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 the next day 18:01:23 to 00:16:23.
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 Joda Time library is a popular Java date and time library that is much better designed than the standard Java date and calendar API; consider this if you need to work with dates and times in Java.
With Joda Time, you can 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");
}
source to share
As a quick and dirty solution:
final DateFormat datos = new SimpleDateFormat("HH:mm:ss");
Date ac;
final Date lim = new Date();
String actual, limit;
actual = "18:01:23";
limit = "00:16:23";
try {
ac = datos.parse(actual);
lim.setTime(ac.getTime() + TimeUnit.MINUTES.toMillis(16) + TimeUnit.SECONDS.toMillis(23));
if ( ac.before(lim) ) {
// TODO
}
} catch ( final ParseException e ) {
e.printStackTrace();
}
source to share