There are several ways to format dates in Java, but by far the easiest is to use DateFormat.
Creating a DateFormat is very similar to NumberFormat that we saw on the previous
page. Here are the static factory methods called directly on the DateFormat class:
There are several overloaded versions of each method above. We will not cover Locale here
as that will be covered in another article on java timezone support. However, there is another parameter
called style, which allows customization of how the date or time is displayed. See the DateFormat
object for a full list. Common styles are SHORT, MEDIUM and LONG.
Output:
30/11/07 22:57
If you need more control over what gets output then you will probably end up using
SimpleDateFormat. This class provides much more detailed means of specifying
how to format a date. A full and complete list of all options is beyond this guide, but can
be found online in the SimpleDateFormat javadocs.
Unlike previous examples where we used a factory method to create the formatting object, in
this case we call new directly to get a new instance, normally passing the required format
string as the parameter. This class uses similar formatting codes to String.format
explained earlier in this article.
Output:
30/Nov/2007
30 November, 2007. 10:58
I hope this has given you insight into formatting various types into Strings, again this article only gets you started with the various classes, there's a lot of extra detail not covered in here.