SimpleDateFormat returns 24-hour date: how to get 12-hour date?

I want current time in millis and then to store it in 12 hour format but with this piece of code I am getting 24 hour format time.

long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy HH:mm:ss a");
dateforrow = dateFormat.format(cal1.getTime());

can anybody suggest modifications to get the desired results?


Solution 1:

Change HH to hh as

long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat(
                                "dd/MM/yyyy hh:mm:ss a");
dateforrow = dateFormat.format(cal1.getTime());

Note that dd/mm/yyyy - will give you minutes instead of the month.

Solution 2:

Referring to SimpleDataFormat JavaDoc:

Letter | Date or Time Component | Presentation | Examples
---------------------------------------------------------
   H   |  Hour in day (0-23)    |    Number    |    0
   h   |  Hour in am/pm (1-12)  |    Number    |    12