Java DateFormat
Jakob Jenkov |
The java.text.DateFormat
class is used to format dates as strings according to
a specific Locale
. Different countries have different standards for how they
format dates. In Denmark dates are written using the format dd-mm-yyyy
, but in
the US they format dates using the format mm-dd-yyyy
.
Creating a DateFormat
You create a DateFormat
using the getDateInstance()
and getTimeInstance()
method of the DateFormat
class.
Here is an example:
Locale locale = new Locale("da", "DK"); DateFormat dateFormat = DateFormat.getDateInstance( DateFormat.DEFAULT, locale);
As you can see, the getDateInstance()
method takes two parameters.
The first parameter tells which date format to use. The second parameter is
the Locale
to use.
The date format parameter can be chosen among the following constants in the
DateFormat
class:
DateFormat.DEFAULT DateFormat.SHORT DateFormat.MEDIUM DateFormat.LONG DateFormat.FULL
Exactly how the formatted date ends up looking for each date format used
depends on the Locale
.
Formatting Dates
Formatting dates is done using the format()
method. Here is an example:
Locale locale = new Locale("da", "DK"); DateFormat dateFormat = DateFormat.getDateInstance( DateFormat.DEFAULT, locale); String date = dateFormat.format(new Date()); System.out.println(date);
The output printed from this code when executed on nov. 1st 2012 would be:
01-11-2012
If executed with a UK
Locale
the output would be:
Nov 1, 2012
Formatting Time
In order to format only time and not the date itself, you need a time instance of the
DateFormat
class. You create such an instance using the getTimeInstance()
method. Here is an example:
Locale locale = new Locale("da", "DK"); DateFormat dateFormat = DateFormat.getTimeInstance( DateFormat.DEFAULT, locale); String date = dateFormat.format(new Date()); System.out.println(date);
The output printed from that code could look like this:
12:43:37
Formatting Date and Time
Formatting a date including both date and time is done using a date-time instance.
You create such an instance using the getDateTimeInstance()
method.
Here is an example:
Locale locale = new Locale("da", "DK"); //Locale locale = new Locale("en", "UK"); DateFormat dateFormat = DateFormat.getDateTimeInstance( DateFormat.DEFAULT,DateFormat.DEFAULT, locale); String date = dateFormat.format(new Date()); System.out.println(date);
Notice that the getDateTimeInstance()
method takes two format
parameters. One for the date, and one for the time.
Here is an example output from this code:
01-11-2012 13:07:08
Tweet | |
Jakob Jenkov |