SimpleDateFormat sdf1 = new SimpleDateFormat(yyyy-MM-dd kk:mm:ss);
SimpleDateFormat sdf2 = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);
Calendar cal = Calendar.getInstance();
Date d = cal.getTime();
System.out.println("Current Time is:"+d);
System.out.println("Time value using kk:" + sdf1.format(d));
System.out.println("Time Value using HH:" + sdf2.format(d));
Result:
Current Time is: Wed Sep 25 00:55:20 IST 2013
Time value using kk : 2013-09-25 24:55:20
Time value using HH : 2013-09-25 00:55:20
Can anyone tell why this behavior changes in the time, when using kk and HH.
and also kk gives 24:55:20, is this be useful any where. To my knowledge, there is only 00:00:00 to 23:59:59 is the time range.
Is there any beyond this range, if so where is the place "kk" will be useful?
From the JavaDocs ...
k - Hour in day (1-24)
H - Hour in day (0-23)
Updated
As for why this would be need/supported...There are any number of reasons, some which might be...
I would suggest the intention was to try and meet as many of the possible formats that the API may encounter/require without attempting to limit the developer or require us to have to write our own API's.
I don't know about you, but I have lots of other things I need to do ;)
This is documented in the SimpleDateFormat
docs:
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)
So, you have 4 different formats for hours. I guess addition of k
and h
was a mistake. They really don't make any sense, and almost never needed.
Use H
for 24-hour formats, and K
for 12-hour format.
There's no reason why there should be an error. k
is documentedin SimpleDateFormat
as a field for:
Hour in day (1-24)
That explains why you get 24 for midnight instead of 00, too. If you don't want values between 01 and 24, don't use kk
in your format string! I can't remember the last time I wanted to use something like that, but presumably it's used in some cases (particularly for values which are always "on the hour" so you get 24:00 instead of 00:00).
Always consult the docs for what format strings mean.
[Kian Fatt, Ting] Buddy the difference is that if you use capital H is zero to 23 (0-23)
, but if you use small letter k is one to 24 (1-24)
. The only difference is this and both is right in showing time. You can look at the java documentation link I have provided below.
Souce: SimpleDateFormat
If you can don't use dates and calendar... it's easy to do mistakes with this classes.
jodatime it's a better solution
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.