57

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?

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
aneela
  • 1,457
  • 3
  • 24
  • 45
  • 4
    (First place to look is the API. Also, try to summarize the issue in the title better: it makes a big first impression.) –  Dec 27 '12 at 10:28
  • 1
    For new readers to this question I recommend you don’t use `SimpleDateFormat` and `Calendar`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). See the last part of [the answer by Arvind Kumar Avinash](https://stackoverflow.com/a/67947328/5772882) (may also use `ZonedDateTime` or `OffsetDateTime`). – Ole V.V. Jun 14 '21 at 17:47

10 Answers10

153

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.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
54

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
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • private String getCurrentTimeStamp() { SimpleDateFormat timestamp = new SimpleDateFormat("yyyyMMddHHmmss"); return timestamp.format(new Date()); } . this will give your 24 hrs fomrat..... in case of yyyyMMddhhmmss will return 12 hr format. – PrinceMidha Feb 09 '18 at 09:17
6

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".

Abdullah Ahmed
  • 293
  • 2
  • 16
Philip
  • 503
  • 7
  • 8
6

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

Jackie
  • 25,199
  • 6
  • 33
  • 24
3

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());
Bhavdip Sagar
  • 1,951
  • 15
  • 27
2

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

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());
nsgocev
  • 4,390
  • 28
  • 37
Manjeet Brar
  • 914
  • 1
  • 9
  • 27
0
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");

use hh in place of HH

Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78
0

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.

Nazmus Saadat
  • 973
  • 9
  • 22
-1

See code example below:

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