Simple Java Time Forms

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 someone tell me why this behavior changes over time when kk and HH are used.

as well as kk gives 24:55:20, this is useful anywhere. As far as I know, there is only 00:00:00 to 23:59:59 - this is a time range.

Are there any outside this range, if so, where is the place “kk” useful?

+4
source share
5 answers

There is no reason why an error should occur. k documentedin SimpleDateFormat as a field for:

Hour a day (1-24)

This explains why you get 24 at midnight instead of 00. If you don't need values ​​between 01 and 24, don't use kk in the format string! I don’t remember the last time I wanted to use something like this, but it was supposedly used in some cases (especially for values ​​that are always “per hour”, so you get 24:00 instead of 00:00).

Always refer to documents for which format strings mean.

+1
source

From JavaDocs ...

k - Hour a day (1-24)
H - Hour a day (0-23)

Update

As for why this is needed / supported ... There are several reasons, some of which may be ...

  • Support for external systems. This allows you to parse date / time strings from different sources, giving the API the flexibility to adapt to the needs of the developer.
  • I do not know about you, but my alarm clock works in 1-24 (1-12) hours;)

I would suggest that the intention was to try to satisfy as many formats as possible that the API might encounter / require without trying to restrict the developer or require us to write our own APIs.

I do not know about you, but I have many other things that I need to do;)

+3
source

This is described in the SimpleDateFormat docs:

H Hour a day (0-23)
k Hour a day (1-24)
k Hour at am / pm (0-11)
H Hour at am / pm (1-12)

So, you have 4 different formats in a few hours. I assume adding k and H was a mistake. They really have no meaning and almost never need.

Use H for 24 hour format and k for 12 hour format.

+3
source

[Kian Fatt, Ting] Buddy, the difference is that if you use capital H is zero to 23 (0-23) , but if you use the small letter k is one to 24 (1-24) . The only difference is that both show the time correctly. You can see the link to the java documentation below.

Souce: SimpleDateFormat

+1
source

If you cannot use dates and calendar ... this is easy to do with these classes.

jodatime is the best solution

0
source