views:

1742

answers:

6

Finally I managed to understand what the problem was.

I should hold on my string 11 PM instead of 23 PM

What I don't understand is why parsing '23:00 PM' with SimpleDateFormat("hh:mm aa") returns 11 a.m.?

My guess is it adds 12 hrs to the parsed date.

I hope there is not much problem.

+2  A: 

I would guess that it does something like:

hours = hours % 12;

to ensure that the hours are in the proper range.

Evan Teran
+6  A: 

You want "HH:mm aa" as your format, if you will be parsing 24-hour time.

public static void main(String[] args) throws ParseException {
    SimpleDateFormat df = new SimpleDateFormat("HH:mm aa");
    final Date date = df.parse("23:00 PM");
    System.out.println("date = " + df.format(date));
}

outputs

date = 23:00 PM
Steve McLeod
A: 

Have you tried HH:mm aa?

HH is for 24 hour while hh is for 12.

thelsdj
+2  A: 

23:00 PM could be thought of as 11 AM the next day. Javascript and PHP work like this pretty much but I can't speak for Java.

Greg
That's what I looks it's happening. Yeap!
OscarRyz
+1  A: 

Here are the formatting options specifed in the javadoc

H     Hour in day (0-23)    
k   Hour in day (1-24)  
K   Hour in am/pm (0-11)  
h   Hour in am/pm (1-12)

Notice that "h" would be for hours 1-12. If you want to handle 1-24, try "k". for 0-23 try "H". But I would not expect valid results if you are putting in impossible data.

Peter Recore
+8  A: 

You should be getting an exception, since "23:00 PM" is not a valid string, but Java's date/time facility is lenient by default, when handling date parsing.

The logic is that 23:00 PM is 12 hours after 11:00 PM, which is 11:00 AM the following day. You'll also see things like "April 31" being parsed as "May 1" (one day after April 30).

If you don't want this behavior, set the lenient property to false on your SimpleDateFormat using DateFormat#setLenient(boolean), and you'll get an exception when passing in invalid date/times.

Jack Leow
Ohh, I've seen that flag before, and never knew that was it all about. :P ( nor care about it )
OscarRyz
Do you now? :)
Jack Leow