SimpleDateFormat sample program in Java

By: Norman Chap  

SimpleDateFormat is a concrete subclass of DateFormat. It allows you to define your own formatting patterns that are used to display date and time information. One of its constructors is shown here:

SimpleDateFormat(String formatString)

The argument formatString describes how date and time information is displayed. An example of its use is given here:

SimpleDateFormat sdf = SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");

In most cases, the number of times a symbol is repeated determines how that data is presented. Text information is displayed in an abbreviated form if the pattern letter is repeated less than four times. Otherwise, the unabbreviated form is used. For example, a zzzz pattern can display Pacific Daylight Time, and a zzz pattern can display PDT. For numbers, the number of times a pattern letter is repeated determines how many digits are presented. For example, hh:mm:ss can present 01:51:15, but h:m:s displays the same time value as 1:51:15.

Finally, M or MM causes the month to be displayed as one or two digits. However, three or more repetitions of M cause the month to be displayed as a text string.

The following program shows how this class is used:

// Demonstrate SimpleDateFormat.
import java.text.*;
import java.util.*;
public class SimpleDateFormatDemo {
public static void main(String args[]) {
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("hh:mm:ss");
sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
sdf = new SimpleDateFormat("E MMM dd yyyy");

Sample output from this program is shown here:

19 Feb 1999 11:51:50 CST
Fri Feb 19 1999

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial