DateFormat class

In this chapter you will learn:

  1. Create DateFormat to format date

Create DateFormat to format date

DateFormat is an abstract class for date/time formatting. It provides the ability to format and parse dates and times.

The getDateInstance() method returns an instance of DateFormat that can format date information.

It is available in these forms:

static final DateFormat getDateInstance( ) 
static final DateFormat getDateInstance(int style) 
static final DateFormat getDateInstance(int style, Locale locale)

The argument style is one of the following values: DEFAULT, SHORT, MEDIUM, LONG, or FULL. These are int constants defined by DateFormat.

The argument locale is one of the static references defined by Locale. If the style and/or locale is not specified, defaults are used.

format() method has several overloaded forms, one of which is shown here:

final String format(Date d)

The argument is a Date object that is to be displayed. The method returns a string containing the formatted information.

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
/*from   j  a  v  a  2 s . c o m*/
public class Main {
  public static void main(String args[]) {
    Date date = new Date();
    DateFormat df;
    df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.JAPAN);
    System.out.println("Japan: " + df.format(date));
    df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.KOREA);
    System.out.println("Korea: " + df.format(date));
    df = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
    System.out.println("United Kingdom: " + df.format(date));
    df = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);
    System.out.println("United States: " + df.format(date));
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to use Java DateFormat to format time