Comparing Time Is Incorrect When Picking 12:00

Comparing time is incorrect when picking 12:00

public static void checkTimes(String start, String end) {
try {
if (LocalTime.parse(start).isBefore(LocalTime.parse(end))) {
System.out.println("test1");// future date - good
} else {
System.out.println("fail2");// old date - bad
}
} catch (DateTimeParseException dtpe) {
System.out.println("error");
}
}

Let’s try it:

    checkTimes("14:00", "12:00");
checkTimes("09:00", "12:00");
checkTimes("12:00", "10:00");
checkTimes("12:00", "15:00");

This prints:

fail2
test1
fail2
test1

I believe this agrees with what you had intended. Note that LocalTime parses your strings without the need for an explicit formatter. Furthermore, if you trust that your combobox only contains valid time strings, you can leave out the try-catch construct since DateTimeParseException is an unchecked exception.

If startTime and endTime are JComboBox, I believe you can even fill LocalTime objects into them. Then you don’t need to parse when the user selects one from each. Your JComboBox will call LocalTime.toString(), which will return a string like 09:00, which in turn the combo box will display and let the user select.

    LocalTime[] times = { LocalTime.of(9, 0), LocalTime.of(10, 0), LocalTime.of(11, 0), 
LocalTime.of(12, 0), LocalTime.of(13, 0), LocalTime.of(14, 0) };
JComboBox<LocalTime> combo = new JComboBox<>(times);

Combo

Unfolded:

Combobox unfolded

I am using LocalTime from java.time, the modern Java date and time API. java.time is generally much nicer to work with than the old and outdated date and time classes like SimpleDateFormat, Date and more.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Datetime comparison is giving incorrect result

hh (ranges 1-12), 12:07 is parsed as 00:07:

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm");
System.out.println(format.parse("5/31/2018 00:07").equals(format.parse("5/31/2018 12:07"))); // true

Use HH (ranges 0-23) instead, it will produce desired result:

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm");
System.out.println(format.parse("5/31/2018 11:49").after(format.parse("5/31/2018 12:07"))); // false

SimpleDateFormat convert date incorrect return value when hour is 12

Aside from the fact you shouldn't be using Date or SimpleDateFormat any more, your error is because you are using hh instead of HH

h -> Hour in am/pm (1-12)

H -> Hour in day (0-23)

Consider using LocalDateTime in your case.

12:xx shown as 00:xx in SimpleDateFormat.format(hh:mm:ss)

First a couple of formatters like yours, only using DateTimeFormatter from java.time, the modern Java date and time API:

private static DateTimeFormatter dtfOld = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static DateTimeFormatter dtfNew = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

Two things to note: (1) Declare the formatters in the logical order, the order in which you are going to use them. Using the opposite order in the question confused me, and I’m unsure whether it confused yourself too. (2) In dtfOld use uppercase HH for hour of day in the interval 00 through 23. Lowercase hh is for hour within AM or PM from 01 through 12 (in this case the same format pattern letters apply for SimpleDateFormat and DateTimeFormatter; there are differences, though). Now the rest is pretty boring, only simpler than your code:

    LocalDateTime parsed = LocalDateTime.parse("2017-03-12 12:33:33", dtfOld);
System.out.println(parsed);
LocalDateTime dateTime = parsed.plusSeconds(10);
System.out.println(dateTime);
System.out.println(dateTime.format(dtfNew));

Output is:

2017-03-12T12:33:33
2017-03-12T12:33:43
12-03-2017 12:33:43

I am recommending java.time. The old date and time classes that you used — SimpleDateFormat, Calendar and Date — are long outdated. It’s not only in this case that the modern classes allow for simpler code, it’s quite common. I find java.time generally so much nicer to work with.

What went wrong in your code?

I gave a hint already: Lowercase hh is for hour within AM or PM from 01 through 12. When you don’t supply and parse an AM/PM marker, AM is used as the default. And 12:33:33 AM means a little more than half an hour past midnight, and is rendered as 00:33:33 on a 24 hour clock.

The times from 13:00 up to 23:59? They don’t exist in AM. Apparently SimpleDateFormat doesn’t care and just extrapolates from the hours from 01 through 11 and therefore happens to give you the time you had expected. There’s a trick to tell it not to; but I wouldn’t want to bother, I’d rather not use the class at all.

Link

Oracle tutorial: Date Time explaining how to use java.time.

Issue with converting String to Date

Change your formatter:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

HH - means hours

Reach to: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html and see all the examples you need.

calculate time difference between two hours in timeformat hh:mm:ss java

The answer by Michael is good (+1). Allow me to add that you don’t need to mention any formatter (though I also see the advantage of being explicit about the format) and you don’t need to invent an artificial and probably incorrect date to deal with the 24:00 issue.

        LocalTime start = LocalTime.parse(timeStart);
LocalTime stop = LocalTime.parse(timeStop);
if (stop.isAfter(start)) { // the normal situation
System.out.println(formatDuration(Duration.between(start, stop)));
} else if (stop.equals(LocalTime.MIDNIGHT)) {
System.out.println(
formatDuration(Duration.between(start, stop).plusDays(1)));
} else {
System.out.println("End time " + timeStop + " was before start time " + timeStart);
}

I am assuming that the times are on the same date except that an end time of 00:00:00 would mean midnight at the end of the day (sometimes called 24.00 where I come from). If you need to calculate, say from 13:00 one day to 13:00 to the next day as 24 hours, just delete the second if condition and the last else block.

Feeding your example input gives the output you asked for:

04:57:15
01:00:00
12:05:00
11:55:00

As Michael mentions, the toMinutesPart and toSecondsPart methods were introduced in Java 9. For how to format the duration in earlier Java versions see my answer here.

What went wrong in your code?

To parse times on a 24 hour clock correctly (12:05:00, 13:00:00, 14:00:00, 15:00:58) you need to use uppercase HH for hour of day. Lowercase hh is for hour within AM or PM from 01 to 12 inclusive. When you don’t specify AM or PM, AM is used as default. So 10:03:43 is parsed as you expected. Funnily 15:00:58 is too even though there is no 15:00:58 AM. SimpleDateFormat just extrapolates. The trouble comes with 12:05:00 since 12:05:00 AM means 00:05:00. On my computer I got 23:55:00 (not 00:05:00, as you said you got). This is because you had first altered the start time into 24:00:00 and next calculated the time from 00:05:00 to 24:00:00, which is 23:55:00. Since you know which time is the start time and which is the end time, you probably shouldn’t swap them in the case where they seem to be in the wrong order. In your last example I got 23:55:00 too. What happens is the same except the times aren’t swapped since 00:05:00 is already before 24:00:00.

Simple Date Format error parsing date

Your calculation looks fine to me so my guess is the issue is the formatting.

Have you tried using

cal.set(Calendar.HOUR_OF_DAY, hours);
cal.set(Calendar.MINUTE, minutes);

and then getting the date with

Date date = cal.getTime();


Related Topics



Leave a reply



Submit