gstanley
gstanley

Reputation: 73

Java SimpleDateFormat issue with kk hour formatting

I understand that kk is supposed to cause hours to range from 1-24. However, there seems to be an issue in how the days change in this formatting.

Here is example code and it's output to illustrate my point:

Long HOUR = 3600000L;

SimpleDateFormat kkFormat = new SimpleDateFormat("yyyy-MM-dd kk");
SimpleDateFormat HHFormat = new SimpleDateFormat("yyyy-MM-dd HH");

Date date = kkFormat.parse("2015-05-20 21");

for(int i=0; i<5; i++){
    System.out.println(kkFormat.format(new Date(date.getTime() + i * HOUR)));
    System.out.println(HHFormat.format(new Date(date.getTime() + i * HOUR)));
    System.out.println();
}

This generates the following output:

2015-05-20 21
2015-05-20 21

2015-05-20 22
2015-05-20 22

2015-05-20 23
2015-05-20 23

2015-05-21 24
2015-05-21 00

2015-05-21 01
2015-05-21 01

The issue that I see is with "2015-05-21 24" should this date not be formatted as "2015-05-20 24".

Thanks for clarifications.

edit: In answer to Dan Getz I'm trying to create file names that iterate as follows:

2015052023.txt

2015052024.txt

2015052101.txt

Upvotes: 3

Views: 248

Answers (1)

Dan Getz
Dan Getz

Reputation: 9135

What day it is, while dependent on time zone, is independent of the way the hours are written. So if the date is the 21st, then the date is the 21st, end of story. Writing "12am" as "00" or "24" is irrelevant to this.

Perhaps you're forgetting that an hour has 60 different minutes in it? It's not just about the first instant that the clock strikes midnight, it's the whole hour after that we're talking about, which is clearly part of the next 24-hour day.

I personally would never use 24 for times after 12am because of this ambiguity. Perhaps you could edit into your question why you'd want to use 24 as the hours for this? Is your data model truly time stamps down to the millisecond or similar? Or are you hoping to store and print something else?

Upvotes: 1

Related Questions