In this section, you will learn how to format the time using a custom format.
In this section, you will learn how to format the time using a custom format.In this section, you will learn how to format the time using a custom format.
Formatting and parsing is now become a simple task. We have so many classes
to format different objects like data, time, message etc. Here we are going to
format the time using a custom format. For this task, the class SimpleDateFormat
is more approriate. It uses unquoted letters from 'A'
to 'Z'
and from 'a'
to 'z'
and interpret them as pattern
letters for representing the components of a date or time string. For
example,
h: It denotes the hour in am/pm.
m: It denotes minute in hour.
s: It denotes the second in minute.
a: It denotes the am/pm marker.
Here is the code:
import java.text.*; import java.util.*; public class FormattingTime { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a"); String dateString = sdf.format(new Date()); System.out.println(dateString); } }
Output:
11:07:37 AM |