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
= simpleDateFormat.parse(datetimestamp
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.
Parameter | Description | Example |
---|---|---|
yyyy | Year 4 digits | 2010 |
yy | Year 2 digits | 10 |
MM | Month 2 digits | 12 |
w | Week of year | 34 |
d | Day in Month | 15 |
HH | Hour (24h-Format) | 13 |
mm | Minute | 05 |
ss | Second | 34 |
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.
Leave a Reply