Displaying AM and PM in lower case after date formatting
Asked Answered
M

11

81

After formatting a datetime, the time displays AM or PM in upper case, but I want it in lower case like am or pm.

This is my code:

public class Timeis {
    public static void main(String s[]) {
        long ts = 1022895271767L;
        String st = null;  
        st = new SimpleDateFormat(" MMM d 'at' hh:mm a").format(ts);
        System.out.println("time is " + ts);  
    }
}
M16 answered 27/11, 2012 at 9:59 Comment(3)
st.toLowerCase() will do it and there is no easier way.Invertebrate
The trouble is that, like month and day names, the AM/PM marker is locale-specific - it may not make sense in some languages to force everything to lower case (leaving aside the fact that some languages just use 24 hour clock for everything and don't really have terms for AM and PM at all).Kristelkristen
For new readers to this question I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use Instant, ZoneId ZonedDateTime and DateTimeFormatter, all from java.time, the modern Java date and time API.Niersteiner
F
92

Unfortunately the standard formatting methods don't let you do that. Nor does Joda. I think you're going to have to process your formatted date by a simple post-format replace.

String str = oldstr.replace("AM", "am").replace("PM","pm");

You could use the replaceAll() method that uses regepxs, but I think the above is perhaps sufficient. I'm not doing a blanket toLowerCase() since that could screw up formatting if you change the format string in the future to contain (say) month names or similar.

EDIT: James Jithin's solution looks a lot better, and the proper way to do this (as noted in the comments)

Foust answered 27/11, 2012 at 10:2 Comment(6)
All answers are correct or near to correct. But ths Answer is simple and meet my criteriaM16
the answer posted by James Jithin is perfect approach to do it.Gretel
I prefer Brian Agnew's solution. It's the Agile approach. The least amount of code that could possibly work.Georgena
a variation timeStr = timeStr.toLowerCase(Locale.UK);Contrary
This answer is not good enough because some phones display AM/PM, others display a.m./p.m. James Jithin response handles that and is therefore better.Longish
For my needs the ColdFusion equivalent of this worked perfectly.Scirrhus
C
103

This works

public class Timeis {
    public static void main(String s[]) {
        long ts = 1022895271767L;
        SimpleDateFormat sdf = new SimpleDateFormat(" MMM d 'at' hh:mm a");
        // CREATE DateFormatSymbols WITH ALL SYMBOLS FROM (DEFAULT) Locale
        DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
        // OVERRIDE SOME symbols WHILE RETAINING OTHERS
        symbols.setAmPmStrings(new String[] { "am", "pm" });
        sdf.setDateFormatSymbols(symbols);
        String st = sdf.format(ts);
        System.out.println("time is " + st);
    }
}
Cordie answered 27/11, 2012 at 10:14 Comment(3)
@BrianAgnew, Not sure, you may try updating the property of the DateFormatSymbols instance received from joda-time.sourceforge.net/api-release/org/joda/time/…Cordie
When specifying Locale in SimpleDateFormate, using DateFormatSymbols messes it up. You would probable have to specifically set all of the symbols and not just am/pm.Chishima
thanks working great, provided in my case need to replace " " with "", e.g hh:mm a to hh:mmaGarek
F
92

Unfortunately the standard formatting methods don't let you do that. Nor does Joda. I think you're going to have to process your formatted date by a simple post-format replace.

String str = oldstr.replace("AM", "am").replace("PM","pm");

You could use the replaceAll() method that uses regepxs, but I think the above is perhaps sufficient. I'm not doing a blanket toLowerCase() since that could screw up formatting if you change the format string in the future to contain (say) month names or similar.

EDIT: James Jithin's solution looks a lot better, and the proper way to do this (as noted in the comments)

Foust answered 27/11, 2012 at 10:2 Comment(6)
All answers are correct or near to correct. But ths Answer is simple and meet my criteriaM16
the answer posted by James Jithin is perfect approach to do it.Gretel
I prefer Brian Agnew's solution. It's the Agile approach. The least amount of code that could possibly work.Georgena
a variation timeStr = timeStr.toLowerCase(Locale.UK);Contrary
This answer is not good enough because some phones display AM/PM, others display a.m./p.m. James Jithin response handles that and is therefore better.Longish
For my needs the ColdFusion equivalent of this worked perfectly.Scirrhus
T
9

If you don't want to do string substitution, and are using Java 8 javax.time:

Map<Long, String> ampm = new HashMap<>();
ampm.put(0l, "am");
ampm.put(1l, "pm");

DateTimeFormatter dtf = new DateTimeFormatterBuilder()
        .appendPattern("E M/d h:mm")
        .appendText(ChronoField.AMPM_OF_DAY, ampm)
        .toFormatter()
        .withZone(ZoneId.of("America/Los_Angeles"));

It's necessary to manually build a DateTimeFormatter (specifying individual pieces), as there is no pattern symbol for lowercase am/pm. You can use appendPattern before and after.

I believe there is no way to substitute the default am/pm symbols, making this is the only way short of doing the string replace on the final string.

Tripos answered 26/2, 2017 at 8:41 Comment(0)
A
7
Calendar c = Calendar.getInstance();

System.out.println("Current time => " + c.getTime());

SimpleDateFormat df = new SimpleDateFormat("HH:mm a");
String formattedDate = df.format(c.getTime());
formattedDate = formattedDate.replace("a.m.", "AM").replace("p.m.","PM");

TextView textView = findViewById(R.id.textView);
textView.setText(formattedDate);
Ashok answered 30/12, 2017 at 9:47 Comment(1)
Simple to the Core. Sure shot procedure.Ashok
D
5

Try this:

System.out.println("time is " + ts.toLowerCase());

Although you may be able to create a custom format as detailed here and here

Unfortunately out of the box the AM and PM do not seem to be customisable in the standard SimpleDateFormat class

Drollery answered 27/11, 2012 at 10:3 Comment(2)
This would make the ntire string to lower case, i guess OP just need lower case am/pm, otherwise, its a good solution :)Yuonneyup
Yes i tried it you are correct @Brian Agnew's answer is very correctM16
P
3
    String today = now.format(new DateTimeFormatterBuilder()
            .appendPattern("MM/dd/yyyy ")
            .appendText(ChronoField.AMPM_OF_DAY)
            .appendLiteral(" (PST)")
            .toFormatter(Locale.UK));

// output => 06/18/2019 am (PST)

Locale.UK => am or pm; Locale.US => AM or PM; try different locale for your needs (defaul, etc.)

Pyxis answered 18/6, 2019 at 13:6 Comment(1)
Setting the Locale did the trick. Thank you!Luckey
P
3
new SimpleDateFormat("MMM d 'at' hh:mm a", new Locale("en", "IN"));

change to a locale that uses am/pm instead of AM/PM.

Proptosis answered 3/8, 2022 at 5:45 Comment(1)
simple and quick for kotlin we can use ` val formatter12Hour = DateTimeFormatter.ofPattern("h:mma", java.util.Locale("en", "IN")) `Ewell
L
2

James's answer is great if you want different style other than default am, pm. But I'm afraid you need mapping between Locale and Locale specific AM/PM set to adopting the override. Now you simply use java built-in java.util.Formatter class. So an easy example looks like this:

System.out.println(String.format(Locale.UK, "%1$tl%1$tp", LocalTime.now()));

It gives:

9pm

To note that if you want upper case, just replace "%1$tp" with "%1$Tp". You can find more details at http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#dt.

Lundquist answered 6/8, 2015 at 21:12 Comment(0)
N
0

just add toLowarCase() like this

public class Timeis {
public static void main(String s[]) {
      long ts = 1022895271767L;
      String st = null;  
      st = new SimpleDateFormat(" MMM d 'at' hh:mm a").format(ts).toLowerCase();
      System.out.println("time is " + ts);  
}
}

and toUpperCase() if you want upper case

Neoclassicism answered 4/4, 2017 at 12:21 Comment(1)
This will lowercase the month also.Hemiterpene
T
0

This is how we perform in android studio's java code pass unix timestamp as parameter

private String convertTimeToTimeStamp(Long timeStamp){
            SimpleDateFormat sdf=new SimpleDateFormat("hh:mm aaa", Locale.getDefault());
            return sdf.format(timeStamp);
        }

function returns time of format 09:30 PM

Turnspit answered 24/11, 2021 at 10:31 Comment(0)
H
0

dateString.toLowerCase();

String timeString= new SimpleDateFormat(" MMM d 'at' hh:mma") .format(timestaamp) .toLowerCase();

System.out.println("time is " + tstimeString);

Hellbender answered 23/6, 2023 at 11:29 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.