Displaying AM and PM in lower case after date formatting

JavaDatetimeSimpledateformat

Java Problem Overview


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);  
    }
}

Java Solutions


Solution 1 - Java

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);
	}
}

Solution 2 - Java

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)

Solution 3 - Java

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.

Solution 4 - Java

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);

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

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

Solution 8 - Java

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

Solution 9 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxrcwrnView Question on Stackoverflow
Solution 1 - JavaJames JithinView Answer on Stackoverflow
Solution 2 - JavaBrian AgnewView Answer on Stackoverflow
Solution 3 - JavaNikola MihajlovićView Answer on Stackoverflow
Solution 4 - JavaMouryaView Answer on Stackoverflow
Solution 5 - JavaRNJView Answer on Stackoverflow
Solution 6 - JavaShenYiView Answer on Stackoverflow
Solution 7 - JavadfosticView Answer on Stackoverflow
Solution 8 - Java3zcsView Answer on Stackoverflow
Solution 9 - JavaShashank PandeyView Answer on Stackoverflow