Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between hh:mm a and HH:mm a

Here is my original code-

String dateString = "23 Dec 2015 1:4 PM";
Locale locale = new Locale("en_US");
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);
Date date = null;

try {
    date = formatter.parse(dateString);
} catch (ParseException e) {
    LOGGER.error(e);
}

String newDate = df.format(date);
System.out.println("oldDate = " + dateString);
System.out.println("newDate = " + newDate);

and here is my output-

oldDate = 23 Dec 2015 1:4 PM
newDate = 23 Dec 2015 01:04 AM

There is AM-PM difference between the oldDate and newDate. Now I changed the DateFormat code to-

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
DateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm a", locale);

and I get the expected output, which is-

oldDate = 23 Dec 2015 1:4 PM
newDate = 23 Dec 2015 01:04 PM

I'm aware that HH signifies the 24 hour format and hh signifies the 12-hour format.

My question is

If I use HH:mm a instead of hh:mm a, shouldn't this be returning the time in 24-hour format?

(or)

If it defaults to 12-hour format, shouldn't it return respective AM/PM marker depending on the date input provided?

This is just for my understanding.

like image 574
AlwaysALearner Avatar asked Dec 23 '15 08:12

AlwaysALearner


2 Answers

Updated Answer

Here the problem is with Program flow

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");

this simple date formatter is used to format the date string the Date object is created, here is the important part of answer

As you are using HH instead of hh, the SimpleDateFormater considers that provided date string is in 24-Hour Format and simply ignores the AM/PM marker here.

The Date Object from constructed from this SimpleDateFormatter is passed to the

DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);

That's why it's printing

newDate = 23 Dec 2015 01:04 AM

if you change the line

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");

with

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");

Everything will go smooth as it should!

Note : when creating a locale you should pass the language code to the Locale() constructor. en-us not en_us.

IMP : Code is tested on Java 8 also. Java(TM) SE Runtime Environment (build 1.8.0_121-b13)

like image 176
Arjun Avatar answered Oct 19 '22 07:10

Arjun


Difference between hh:mm and HH:mm:

  HH:mm => will look like 00:12, 23:00... this has 24 hour format.

  hh:mm => will look like 01:00Am, 02:00Am,...01:00pm this has 12 hour format.

And the a in hh:mm a or in HH:mm a is Am/pm marker for more info go to link

like image 20
Abdelhak Avatar answered Oct 19 '22 08:10

Abdelhak