In this tutorial we will see how to display time in 12 hour format with AM/PM using the SimpleDateFormat.
1. Display current date and time in 12 hour format with AM/PM
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.
hh – hours in 12 hour format
mm – minutes
aa – AM/PM marker.
In this example we are displaying current date and time with AM/PM marker.
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
class Example
{
public static void main(String[] args)
{
//Displaying current time in 12 hour format with AM/PM
DateFormat dateFormat = new SimpleDateFormat("hh.mm aa");
String dateString = dateFormat.format(new Date()).toString();
System.out.println("Current time in AM/PM: "+dateString);
//Displaying current date and time in 12 hour format with AM/PM
DateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy hh.mm aa");
String dateString2 = dateFormat2.format(new Date()).toString();
System.out.println("Current date and time in AM/PM: "+dateString2);
}
}
Output:
Current time in AM/PM: 12.30 PM Current date and time in AM/PM: 20/10/2017 12.30 PM
2. Displaying given date and time with AM/PM
In the above example, we are showing the current date and time with AM/PM. In this example we are displaying the given date and time with AM/PM.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
class Example
{
public static void main(String[] args)
{
//Displaying given time in 12 hour format with AM/PM
String dateString3 = "22.30";
//old format
SimpleDateFormat sdf = new SimpleDateFormat("HH.mm");
try{
Date date3 = sdf.parse(dateString3);
//new format
SimpleDateFormat sdf2 = new SimpleDateFormat("hh.mm aa");
//formatting the given time to new format with AM/PM
System.out.println("Given time in AM/PM: "+sdf2.format(date3));
}catch(ParseException e){
e.printStackTrace();
}
//Displaying given time in 12 hour format with AM/PM
String dateString4 = "21/12/2016 21.20";
//old format
SimpleDateFormat sdf3 = new SimpleDateFormat("dd/MM/yyyy HH.mm");
try{
Date date4 = sdf3.parse(dateString4);
//new format
SimpleDateFormat sdf4 = new SimpleDateFormat("dd/MM/yyyy hh.mm aa");
//formatting the given time to new format with AM/PM
System.out.println("Given date and time in AM/PM: "+sdf4.format(date4));
}catch(ParseException e){
e.printStackTrace();
}
}
}
Output:
Given time in AM/PM: 10.30 PM Given date and time in AM/PM: 21/12/2016 09.20 PM
Leave a Reply