Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying AM and PM in lower case after date formatting

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);       } } 
like image 436
xrcwrn Avatar asked Nov 27 '12 09:11

xrcwrn


People also ask

How do I display AM PM in date format?

There are two patterns that we can use in SimpleDateFormat to display time. Pattern “hh:mm aa” and “HH:mm aa”, here HH is used for 24 hour format without AM/PM and the hh is used for 12 hour format with AM/PM. aa – AM/PM marker. In this example we are displaying current date and time with AM/PM marker.


2 Answers

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);     } } 
like image 183
James Jithin Avatar answered Oct 06 '22 00:10

James Jithin


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)

like image 31
Brian Agnew Avatar answered Oct 06 '22 00:10

Brian Agnew