Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

java - Comparing time is incorrect when picking 12:00

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..

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...