Display current time in 12 hour format with AM/PM
Asked Answered
R

15

248

Currently the time displayed as 13:35 PM However I want to display as 12 hour format with AM/PM, i.e 1:35 PM instead of 13:35 PM

The current code is as below

private static final int FOR_HOURS = 3600000;
private static final int FOR_MIN = 60000;
public String getTime(final Model model) {
    SimpleDateFormat formatDate = new SimpleDateFormat("HH:mm a");
    formatDate.setTimeZone(userContext.getUser().getTimeZone());
    model.addAttribute("userCurrentTime", formatDate.format(new Date()));
    final String offsetHours = String.format("%+03d:%02d", userContext.getUser().getTimeZone().getRawOffset()
    / FOR_HOURS, Math.abs(userContext.getUser().getTimeZone().getRawOffset() % FOR_HOURS / FOR_MIN));
    model.addAttribute("offsetHours",
                offsetHours + " " + userContext.getUser().getTimeZone().getDisplayName(Locale.ROOT));
    return "systemclock";
}
Retrocede answered 11/9, 2013 at 6:48 Comment(1)
Try SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");Em
V
554

Easiest way to get it by using date pattern - h:mm a, where

  • h - Hour in am/pm (1-12)
  • m - Minute in hour
  • a - Am/pm marker

Code snippet :

DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

Read more on documentation - SimpleDateFormat java 7

Vacuous answered 11/9, 2013 at 6:49 Comment(7)
Note that using two h's ("hh") gives you a leading zero (i.e. 01:23 AM). One "h" gives you the hour without the leading zero (1:23 AM).Criswell
How to get AM&PM instead of 'a.m' & 'p.m'Baudin
@akashbs I think there's no easy way around but you can try something like: in your full date string, call substring from (length - 4) to (length -1) and save it in a variable_original then create a new variable_modified that will use the first created variable_original and replaces ".m" with "m", then call the method toUpperCase after that return to your full date string and call replace(variable_original, variable_modified) this will achieve what you're looking forCrissycrist
@akashbs But you can use locals, each local uses different date formats, I believe using the US local can achieve what you're looking for tooCrissycrist
@akashbs For more info check these docs: developer.android.com/reference/java/text/SimpleDateFormatCrissycrist
im having problem where 12:03pm became 00:03 pmSpotty
For AM/PM I am using "a" but as result, it is in small letters like am/pm. Why?Newfeld
E
124

Use this SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

enter image description here

Java docs for SimpleDateFormat

Em answered 11/9, 2013 at 6:53 Comment(1)
Outmoded now. These formatting codes are now supplanted by the formatting codes of the DateTimeFormatter class, per JSR 310.Bolide
J
85

use "hh:mm a" instead of "HH:mm a". Here hh for 12 hour format and HH for 24 hour format.

Live Demo

Jay answered 11/9, 2013 at 6:54 Comment(3)
Thanks @RuchiraGayanRanaweei... i just wondering to capture the 24 format and convert it into the AM/PM format...Opal
This is important. I just had a case where "Nov 18 2016 5:28PM" was converted to "2016-11-18T05:28:00" instead of "2016-11-18T17:28:00" because I used the wrong hour placeholder. Thanks!Bengali
this saved me, I was wondering why I was getting dates like 08/25/2022 13:52 pm now I know,Univalve
J
38
SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm:ss a");
  • h is used for AM/PM times (1-12).

  • H is used for 24 hour times (1-24).

  • a is the AM/PM marker

  • m is minute in hour

Note: Two h's will print a leading zero: 01:13 PM. One h will print without the leading zero: 1:13 PM.

Looks like basically everyone beat me to it already, but I digress

Jennettejenni answered 29/12, 2015 at 19:13 Comment(0)
A
21
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa");
String formattedDate = dateFormat.format(new Date()).toString();
System.out.println(formattedDate);

Output: 11-Sep-13 12.25.15.375 PM

Angara answered 11/9, 2013 at 6:55 Comment(0)
D
14
// hh:mm will print hours in 12hrs clock and mins (e.g. 02:30)
System.out.println(DateTimeFormatter.ofPattern("hh:mm").format(LocalTime.now()));

// HH:mm will print hours in 24hrs clock and mins (e.g. 14:30)
System.out.println(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.now())); 

// hh:mm a will print hours in 12hrs clock, mins and AM/PM (e.g. 02:30 PM)
System.out.println(DateTimeFormatter.ofPattern("hh:mm a").format(LocalTime.now())); 
Dielle answered 18/9, 2017 at 21:20 Comment(2)
well, this is the best answer that I found here, thanksHarrod
this is what I wantBeaut
E
10

Using Java 8:

LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(localTime.format(dateTimeFormatter));

The output is in AM/PM Format.

Sample output:  3:00 PM
Emlynne answered 29/9, 2017 at 9:39 Comment(1)
Specify a Locale by calling withLocale on that formatter object, to determine the human language and cultural norms to use in generating the AM/PM text.Bolide
B
9

tl;dr

Let the modern java.time classes of JSR 310 automatically generate localized text, rather than hard-coding 12-hour clock and AM/PM.

LocalTime                                     // Represent a time-of-day, without date, without time zone or offset-from-UTC.
.now(                                         // Capture the current time-of-day as seen in a particular time zone.
    ZoneId.of( "Africa/Casablanca" )          
)                                             // Returns a `LocalTime` object.
.format(                                      // Generate text representing the value in our `LocalTime` object.
    DateTimeFormatter                         // Class responsible for generating text representing the value of a java.time object.
    .ofLocalizedTime(                         // Automatically localize the text being generated.
        FormatStyle.SHORT                     // Specify how long or abbreviated the generated text should be.
    )                                         // Returns a `DateTimeFormatter` object.
    .withLocale( Locale.US )                  // Specifies a particular locale for the `DateTimeFormatter` rather than rely on the JVM’s current default locale. Returns another separate `DateTimeFormatter` object rather than altering the first, per immutable objects pattern.
)                                             // Returns a `String` object.

10:31 AM

Automatically localize

Rather than insisting on 12-hour clock with AM/PM, you may want to let java.time automatically localize for you. Call DateTimeFormatter.ofLocalizedTime.

To localize, specify:

  • FormatStyle to determine how long or abbreviated should the string be.
  • Locale to determine:
    • The human language for translation of name of day, name of month, and such.
    • The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Here we get the current time-of-day as seen in a particular time zone. Then we generate text to represent that time. We localize to French language in Canada culture, then English language in US culture.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalTime localTime = LocalTime.now( z ) ;

// Québec
Locale locale_fr_CA = Locale.CANADA_FRENCH ;  // Or `Locale.US`, and so on.
DateTimeFormatter formatterQuébec = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_fr_CA ) ;
String outputQuébec = localTime.format( formatterQuébec ) ;

System.out.println( outputQuébec ) ;

// US
Locale locale_en_US = Locale.US ;  
DateTimeFormatter formatterUS = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_en_US ) ;
String outputUS = localTime.format( formatterUS ) ;

System.out.println( outputUS ) ;

See this code run live at IdeOne.com.

10 h 31

10:31 AM

Bolide answered 3/9, 2019 at 1:42 Comment(3)
The 310 Android Back Port library also supports this API if you can't or haven't moved to java.time.Motorcade
@WillVanderhoef Actually, Android 26+ comes with an implementation of java.time. For earlier Android, the latest tooling brings much of the java.time functionality via "API desugaring".Bolide
While that's true, it doesn't change the fact that projects that cannot use java.time and some people might benefit from knowing that a (near?) identical API exists in 310ABP. I know of a project that is stuck in this state until a dependency is updated to use java.time.Motorcade
A
7

If you want current time with AM, PM in Android use

String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime());

If you want current time with am, pm

String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime()).toLowerCase();

OR

From API level 26

LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
String time = localTime.format(dateTimeFormatter);
Artiste answered 30/1, 2019 at 5:32 Comment(5)
In 2019 please don’t teach the young ones to use the long outdated and notoriously troublesome SimpleDateFormat class. At least not as the first option. And not without any reservation. Today we have so much better in java.time, the modern Java date and time API and its DateTimeFormatter.Cromer
Thanks. The modern answer can be used on low API levels too if you add ThreeTenABP, the backport of java.time, to your Android project. See How to use ThreeTenABP in Android Project (for a simple task like this one, the value may be debatable, but for just slightly more date and time work I recommend it).Cromer
Since AM and PM are hardly used in other languages than English, I’d probably use DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH) (or another English-speaking locale).Cromer
@OleV.V. : Nothing is better than using a code that is compatible with all generations. SimpleDateFormat is legacy and will stay foreverKnurled
I probably could not disagree more, @BhavikMehta. I do not expect SimpleDateFormat to stay in all future Java versions, at least not without deprecation. The value of keeping code compatible with Java 1.4 is non-existing. And keeping hard-to-maintain code -- certainly is not the best thing in the world.Cromer
B
6

Just replace below statement and it will work.

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");
Bedford answered 11/9, 2013 at 8:56 Comment(0)
U
3
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

public class Main {
   public static void main(String [] args){
       try {
            DateFormat parseFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm a");
            String sDate = "22-01-2019 13:35 PM";
            Date date = parseFormat.parse(sDate);
            SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
            sDate = displayFormat.format(date);
            System.out.println("The required format : " + sDate);
        } catch (Exception e) {}
   }
}

- Using java 8

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Main
{
    public static void main(String[] args)
    {
        String pattern = "hh:mm:ss a";
        
        //1. LocalTime
        LocalTime now = LocalTime.now();
        System.out.println(now.format(DateTimeFormatter.ofPattern(pattern)));

        //2. LocalDateTime
        LocalDateTime nowTime = LocalDateTime.now();
        System.out.println(nowTime.format(DateTimeFormatter.ofPattern(pattern)));
    }
}
Uphill answered 22/1, 2019 at 11:9 Comment(1)
You're eating an exception. The Exception handler should at least provide a warning.Cuff
C
2
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");

This will display the date and time

Cockroach answered 23/4, 2015 at 14:34 Comment(0)
H
2
    //To get Filename + date and time


    SimpleDateFormat f = new SimpleDateFormat("MMM");
    SimpleDateFormat f1 = new SimpleDateFormat("dd");
    SimpleDateFormat f2 = new SimpleDateFormat("a");

    int h;
         if(Calendar.getInstance().get(Calendar.HOUR)==0)
            h=12;
         else
            h=Calendar.getInstance().get(Calendar.HOUR)

    String filename="TestReport"+f1.format(new Date())+f.format(new Date())+h+f2.format(new Date())+".txt";


The Output Like:TestReport27Apr3PM.txt
Haigh answered 27/4, 2015 at 10:20 Comment(1)
Way too convoluted and unintuitive. If you must use the deprecated SimpleDateFormat, at least put everything in one call. Also please explain why you use 12 instead of the actual hour from midnight to 1. Also, nobody asked about file names.Instinct
B
1

To put your current mobile date and time format in

Feb 9, 2018 10:36:59 PM

Date date = new Date();
 String stringDate = DateFormat.getDateTimeInstance().format(date);

you can show it to your Activity, Fragment, CardView, ListView anywhere by using TextView

` TextView mDateTime;

  mDateTime=findViewById(R.id.Your_TextViewId_Of_XML);

  Date date = new Date();
  String mStringDate = DateFormat.getDateTimeInstance().format(date);
  mDateTime.setText("My Device Current Date and Time is:"+date);

  `
Brit answered 9/2, 2018 at 17:26 Comment(0)
G
0
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");

("hh:mm:ss a") >>> Here if we don't use 'a' then 24hours will be appeared. so if we want to AM/PM in your time just add this format. if any confusion please let me know.

Gehlenite answered 6/12, 2015 at 8:52 Comment(2)
It's more useful if you explain a little about your answer.Cartoon
("hh:mm:ss a") >>> Here if wedont use a then 24hours will be appeared. so if we want to AM/PM in your time just add this format. if any confusion please let me know.Gehlenite

© 2022 - 2024 — McMap. All rights reserved.