239

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";
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
ronan
  • 4,492
  • 13
  • 47
  • 67

15 Answers15

539

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

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • 75
    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). – Ben Jakuben Dec 02 '14 at 19:19
  • 12
    How to get AM&PM instead of 'a.m' & 'p.m' – akash bs Feb 13 '18 at 09:10
  • @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 for – Tamim Attafi Dec 30 '19 at 15:12
  • @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 too – Tamim Attafi Dec 30 '19 at 15:14
  • @akashbs For more info check these docs: https://developer.android.com/reference/java/text/SimpleDateFormat – Tamim Attafi Dec 30 '19 at 15:14
  • im having problem where 12:03pm became 00:03 pm – Muhammad Asyraf Jan 31 '20 at 10:42
  • For AM/PM I am using "a" but as result, it is in small letters like am/pm. Why? – Shyamaly Lakhadive Feb 15 '21 at 10:10
123

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

enter image description here

Java docs for SimpleDateFormat

Tarsem Singh
  • 14,139
  • 7
  • 51
  • 71
  • 1
    Outmoded now. These formatting codes are now supplanted by the formatting codes of the [`DateTimeFormatter`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html) class, per JSR 310. – Basil Bourque Sep 03 '19 at 01:45
84

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

Live Demo

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • Thanks @RuchiraGayanRanaweei... i just wondering to capture the 24 format and convert it into the AM/PM format... – gumuruh Aug 06 '14 at 03:26
  • 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! – Kekzpanda Aug 24 '18 at 09:05
  • this saved me, I was wondering why I was getting dates like 08/25/2022 13:52 pm now I know, – Nakshtra Aug 28 '22 at 16:59
37
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

Johnny K
  • 379
  • 3
  • 2
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

MansoorShaikh
  • 913
  • 1
  • 6
  • 19
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())); 
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Panduka
  • 363
  • 2
  • 8
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
Somnath Musib
  • 3,548
  • 3
  • 34
  • 47
Bala
  • 391
  • 4
  • 6
  • 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. – Basil Bourque Sep 03 '19 at 01:22
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

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • The 310 Android Back Port library also supports this API if you can't or haven't moved to java.time. – Will Vanderhoef Apr 22 '22 at 18:13
  • @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". – Basil Bourque Apr 22 '22 at 19:06
  • 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. – Will Vanderhoef May 19 '22 at 21:41
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);
OhhhThatVarun
  • 3,981
  • 2
  • 26
  • 49
MarGin
  • 2,078
  • 1
  • 17
  • 28
  • 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](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jan 30 '19 at 16:24
  • 1
    Thanks. The modern answer can be used on low API levels too if you add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP), the backport of java.time, to your Android project. See [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/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). – Ole V.V. Jan 31 '19 at 05:58
  • 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). – Ole V.V. Jan 31 '19 at 06:02
  • @OleV.V. : Nothing is better than using a code that is compatible with all generations. SimpleDateFormat is legacy and will stay forever – Bhavik Mehta Aug 12 '22 at 07:17
  • 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. – Ole V.V. Aug 12 '22 at 07:26
6

Just replace below statement and it will work.

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");
Tarsem Singh
  • 14,139
  • 7
  • 51
  • 71
user2481237
  • 299
  • 2
  • 3
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)));
    }
}
2
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");

This will display the date and time

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
gopal
  • 29
  • 1
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
alaguvel c
  • 29
  • 2
  • 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. – Robert Sep 03 '19 at 02:02
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);

  `
pirho
  • 11,565
  • 12
  • 43
  • 70
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.

Raju Ahmed
  • 155
  • 1
  • 8