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

JavaAndroidSimpledateformat

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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 - Java

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

Solution 3 - Java

I re-encounter this in the hard way as well. H vs h, for 24-hour vs 12 hour !

Solution 4 - Java

Yep, confirmed that simply using "hh" instead of "HH" fixed my issue, Since "hh" is for 12-Hour Format & "HH" is for 24-Hour Format.

Changed from this:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm aa");

To this:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

You can still use "HH" to store the time if you don't want to bother storing and dealing with the AM/PM. Then when you retrieve it, use "hh".

Solution 5 - Java

Hi I tested below code that worked fine :

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

Solution 6 - Java

There are three major problems with your code:

  1. Using m [Minute in hour] at the place of M [Month in year].
  2. Using H [Hour in day (0-23)] instead of h [Hour in am/pm (1-12)]. Check the documentation to learn more about these two points.
  3. Not using Locale with SimpleDateFormat. Check Never use SimpleDateFormat or DateTimeFormatter without a Locale to learn more about it.

So, the instantiation with the correct format would be:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.ENGLISH);

java.time

Note that the java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*, released in March 2014 as part of Java SE 8 standard library.

Solution using java.time, the modern Date-Time API:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
	public static void main(String[] args) {
		OffsetDateTime odt = OffsetDateTime.now(ZoneOffset.UTC);
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu hh:mm:ss a", Locale.ENGLISH);
		String formatted = dtf.format(odt);
		System.out.println(formatted);
	}
}    

Here, you can use y instead of u but I prefer u to y.

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Solution 7 - Java

You can try it like this

  Calendar c= Calendar.getInstance();

  SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
  String str=sdf.format(c.getTime());

Solution 8 - Java

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");

use hh in place of HH

Solution 9 - Java

Simply follow the code

public static String getFormatedDate(String strDate,StringsourceFormate,
                                     String destinyFormate) {
    SimpleDateFormat df;
    df = new SimpleDateFormat(sourceFormate);
    Date date = null;
    try {
        date = df.parse(strDate);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    df = new SimpleDateFormat(destinyFormate);
    return df.format(date);

}

and pass the value into the function like that,

getFormatedDate("21:30:00", "HH:mm", "hh:mm aa");

or checkout this documentation SimpleDateFormat for StringsourceFormate and destinyFormate.

Solution 10 - Java

See code example below:

SimpleDateFormat df = new SimpleDateFormat("hh:mm");
String formattedDate = df.format(new Date());
out.println(formattedDate);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaneelaView Question on Stackoverflow
Solution 1 - JavaMysticMagicϡView Answer on Stackoverflow
Solution 2 - JavaEng.FouadView Answer on Stackoverflow
Solution 3 - JavaengineerView Answer on Stackoverflow
Solution 4 - JavaPhilipView Answer on Stackoverflow
Solution 5 - JavaBhavdip SagarView Answer on Stackoverflow
Solution 6 - JavaArvind Kumar AvinashView Answer on Stackoverflow
Solution 7 - JavaManjeet BrarView Answer on Stackoverflow
Solution 8 - JavaRam kiran PachigollaView Answer on Stackoverflow
Solution 9 - JavaNazmus SaadatView Answer on Stackoverflow
Solution 10 - JavasyamalaView Answer on Stackoverflow