Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 769
aneela Avatar asked Dec 27 '12 10:12

aneela


People also ask

How do I convert my Android 24 hour clock to 12 hour time?

Tap Set. Tap Use 24- Hour Format to change the format to 24-hour time. Note that the time on the Notification bar reflects the change. You can return to 12-hour time by tapping Use 24-Hour Format again.

How do you get the current time in 24 hour format?

You can use SimpleDateFormat to format it the way you like, this works: SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); String str = sdf. format(new Date()); Also Android version of docs.

Which converter is used for a date and time conversion hours in 12 hour clock?

The pattern dd/MM/yyyy hh:mm:ss aa is used for the 12 hour format and the pattern MM-dd-yyyy HH:mm:ss is used for the 24 hour format. In this program we are changing the format of the date by changing the patterns and formatting the input date.


2 Answers

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.

like image 105
MysticMagicϡ Avatar answered Sep 22 '22 05:09

MysticMagicϡ


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 
like image 38
Eng.Fouad Avatar answered Sep 18 '22 05:09

Eng.Fouad