Java date formatting with SimpleDateFormat

Date formatting in Java can be done in different ways. A fairly simple option is to use the SimpleDateFormat formatting class. This class allows you to format output appropriately and parse input correctly. Below I have put together some small examples of formatting dates and times in Java applications.

Output current Date

The following short lines are necessary to output the current date including the appropriate format:

Date datetimestamp = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy");
System.out.println("Date: " + simpleDateFormat.format(datetimestamp));

A timestamp object is created using new Date() and the formatting day.month.year is specified. The order of the output can be easily changed. A time can also be displayed. A list of some possible definitions can be found at the end of this page.

Date datetimestamp = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println("Datum: " + simpleDateFormat.format(datetimestamp));

Input a specific date

Analogous to the output, strings with a date can also be read in using Java’s SimpleDateFormat. In the following example, I have omitted exception handling for the sake of clarity:
String dateString = "23.02.2012 23:11:00";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
Date datetimestamp = simpleDateFormat.parse(dateString);
System.out.println(datetimestamp);

Due to the lack of internationalization, the example should output the following datetimestamp: Thu Feb 23 23:11:00 CET 2012. This is the standard output of the toString()-method of the Date class.

Formatting mask

As with my database blog posts, here is an overview of what I consider to be the most important formatting instructions for the SimpleDateFormat class presented above.

ParameterDescriptionExample
yyyyYear 4 digits2010
yyYear 2 digits10
MMMonth 2 digits12
wWeek of year34
dDay in Month15
HHHour (24h-Format)13
mmMinute05
ssSecond34

More examples and formatting parameters can be found here and here. Many parameters can be varied by the number of letters. For example, the minute with a leading 0 can be displayed for single-digit minute values if the “m” is written twice. If it is simply written once, no leading 0 is output for single-digit minute values.

Date

Leave a Reply

Your email address will not be published. Required fields are marked *