Programming Tips - Java: Display the time with am/pm

Date: 2014apr28 Update: 2025sep21 Language: Java Level: novice Q. Java: Display the time with am/pm A. Here is a full example showing how to do it:
import java.util.Date; import java.text.SimpleDateFormat; class Demo { private static SimpleDateFormat fmtTime = new SimpleDateFormat("h:mma"); // h = hour without leading zero (because that's ugly) // mm = 2 digit minute // a = AM or PM (I make it lowercase since that looks nicer) static String getTimeStr() { Date date = new Date(); return fmtTime.format(date).toLowerCase(); } public static void main(String []args) { System.out.println("out=" + getTimeStr()); } }
Output:
out=11:20am