By hDDen


2018-04-26 12:21:46 8 Comments

I am creating a booking system and I don't want to allow users to book with starting time 11:00 and end time 09:00 (past)(I am using 24hour clock). I have two combo boxes filled with Strings that act as start and end time (09:00,10:00,11:00,12:00,13:00....)

I have this code:

 String start = (String) startTime.getSelectedItem();
        String end = (String) endTime.getSelectedItem();
        try {
            if(new SimpleDateFormat("hh:mm").parse(start).before(new SimpleDateFormat("hh:mm").parse(end))){
                System.out.println("test1");// future date - good

            }else{
                System.out.println("fail2");// old date - bad
            }
        } catch (ParseException ex) {
                System.out.println("error");
        }

This works perfectly except when I pick start/end time to be 12:00. Program outputs opposite of what it is supposed to output and I am unsure why.

If I pick start time 14:00 and end time 12:00 the program will output fail2(good output),

If I pick start time 09:00 and end time 12:00 the program will output fail2(should be test1),

if I pick start time 12:00 and end time 10:00 the program will output test1(should be fail2),

if I pick start time 12:00 and end time 15:00 the program will output test1(good output)

This type of problem only occurs when I pick 12:00..

3 comments

@Ole V.V. 2018-04-26 15:12:42

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.

@Jeff Learman 2018-04-26 15:36:46

This is a far better solution than one that can't support booking intervals that span midnight. Disallowing spanning midnight makes it much more complicated to support users from any time zone. The question is what do you really want: to compare numbers or to compare times? This is the solution that actually compares times rather than relatively arbitrary numbers that happen to represent portions of the time. (That arbitrariness is part of why your original solution didn't work.)

@hDDen 2018-05-10 13:46:58

Thank you so much for this great explanation of your answer.

@hDDen 2018-04-26 12:27:20

String start = (String) startTime.getSelectedItem();
        String end = (String) endTime.getSelectedItem();
        SimpleDateFormat timer = new SimpleDateFormat("HH:mm");

        try {
            Date startD = timer.parse(start);
            Date endD = timer.parse(end);
            if(startD.before(endD)){
                System.out.println("test1");// future date - good
            }else{
                System.out.println("fail2");// old date - bad
            }
        } catch (ParseException ex) {
                System.out.println("error");
    }

Changing my code to this fixed this issue..

@andy 2018-04-26 12:29:36

No, @user6690200 's answer is the correct explanation.

@Ole V.V. 2018-04-26 13:39:37

@andy Would it be possible that there are two answers providing the correct answer? And both of them using the long outdated and notoriously troublesome SimpleDateFormat class, BTW. Thank you anyway, hDDen, for providing your solution for us all.

@user6690200 2018-04-26 14:08:55

@OleV.V. This answer is actually using HH, just like I posted. So they are basiclly the same one.

@andy 2018-04-26 22:45:01

@hDDen you first wrote that usage of two SimpleDateFormat instances solved the issue. I think you have deleted this sentence. That was what I was referring to. The solution is „HH:mm“ instead. So your answer is correct now. (Ignoring the fact of outdatedness of SimpleDateFormat)

@user6690200 2018-04-26 12:26:44

You should use HH:mm.

hh ranges 01-12, while HH ranges 1-23.

Update

Check the doc of SimpleDateFormat:

H: Hour in day (0-23)

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

@hDDen 2018-04-26 14:05:19

This answer solves the issue too. Thank you @user6690200

@user6690200 2018-04-26 14:06:21

@hDDen I have to remind you, in your answer, you are using HH... While in your question, it is hh

@hDDen 2018-04-26 14:09:51

I didnt know before that this makes a difference, now I know. Thank you again.

@user6690200 2018-04-26 14:11:21

@hDDen No problem :)

@Jeff Learman 2018-04-26 15:39:27

This answer points out why your implementation fails, for practical purposes isn't the best solution as it disallows intervals that span midnight. It's a great answer to your question, but is not the best solution.

Related Questions

Sponsored Content

38 Answered Questions

[SOLVED] Compare two dates with JavaScript

37 Answered Questions

[SOLVED] Calculate relative time in C#

10 Answered Questions

[SOLVED] Why is subtracting these two times (in 1927) giving a strange result?

  • 2011-07-27 08:15:58
  • Freewind
  • 661468 View
  • 6886 Score
  • 10 Answer
  • Tags:   java date timezone

42 Answered Questions

[SOLVED] How to get the current time in Python

  • 2009-01-06 04:54:23
  • user46646
  • 3369298 View
  • 2970 Score
  • 42 Answer
  • Tags:   python datetime time

33 Answered Questions

[SOLVED] When to use LinkedList over ArrayList in Java?

28 Answered Questions

[SOLVED] How to get the current date/time in Java

  • 2011-03-03 01:48:09
  • user496949
  • 1747830 View
  • 708 Score
  • 28 Answer
  • Tags:   java datetime

14 Answered Questions

[SOLVED] Comparing Java enum members: == or equals()?

  • 2009-11-17 17:26:27
  • Matt Ball
  • 683018 View
  • 1760 Score
  • 14 Answer
  • Tags:   java enums

37 Answered Questions

[SOLVED] How do I get the current date and time in PHP?

  • 2009-01-22 20:09:18
  • Mike
  • 2381220 View
  • 865 Score
  • 37 Answer
  • Tags:   php datetime

2 Answered Questions

[SOLVED] How to format java time properly

  • 2014-12-12 08:42:26
  • agarwal_achhnera
  • 790 View
  • 1 Score
  • 2 Answer
  • Tags:   java date

Sponsored Content