Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Simple Date Format Time Issues

Tags:

java

datetime

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?

like image 532
Mohan Avatar asked Feb 16 '23 04:02

Mohan


2 Answers

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.

like image 199
Rohit Jain Avatar answered Feb 17 '23 17:02

Rohit Jain


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

  • Providing support for external systems. This makes it possible to parse date/time strings from a variety of sources, providing the API with the flexibility to adapt to the needs of the developer.
  • I don't know about you, but my alarm clock works in 1-24 (1-12) hour mode ;)

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 ;)

like image 28
MadProgrammer Avatar answered Feb 17 '23 16:02

MadProgrammer