Parsing and Formatting Dates in Java
Jakob Jenkov |
It is possible to both parse dates from strings, and format dates
to strings, using Java's java.text.SimpleDateFormat
class.
I have covered SimpleDateFormat
in more detail in my
Java Internationalization
tutorial, in the text SimpleDateFormat.
It is also possible to parse and format dates using the newer Java DateTimeFormatter which is able to parse and format dates from and to the newer date time classes added in Java 8.
Even though both classes for parsing and formatting dates are covered in more detail in their own texts, I will show you a few examples of how to use them below.
SimpleDateFormat Example
Here is an example of how to format and parse a date using the SimpleDateFormat
class.
The SimpleDateFormat
class works on java.util.Date
instances.
Here are two simple examples:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String dateString = format.format( new Date() ); Date date = format.parse ( "2009-12-31" );
The string passed as parameter to the SimpleDateFormat
class is a pattern
that tells how the instance is to parse and format dates. In the example above I used
the pattern "yyyy-MM-dd" which means 4 digits for the year (yyyy), two digits for month (MM)
and two digits for day(dd). The digit groups are separated by dashes (-) because I specified
that in the pattern too, between the digit groups.
Below is a list of the most common pattern letters you can use. For a full list, see the official
JavaDoc for the SimpleDateFormat
class.
y = year (yy or yyyy) M = month (MM) d = day in month (dd) h = hour (0-12) (hh) H = hour (0-23) (HH) m = minute in hour (mm) s = seconds (ss) S = milliseconds (SSS) z = time zone text (e.g. Pacific Standard Time...) Z = time zone, time offset (e.g. -0800)
Here are a few pattern examples, with examples of how each pattern would format or expect to parse a date:
yyyy-MM-dd (2009-12-31) dd-MM-YYYY (31-12-2009) yyyy-MM-dd HH:mm:ss (2009-12-31 23:59:59) HH:mm:ss.SSS (23:59.59.999) yyyy-MM-dd HH:mm:ss.SSS (2009-12-31 23:59:59.999) yyyy-MM-dd HH:mm:ss.SSS Z (2009-12-31 23:59:59.999 +0100)
DateTimeFormatter Example
Another way to format dates is to use the DateTimeFormatter
which works with the newer date time
classes added in Java 8. Here is a DateTimeFormatter
example of formatting a date as a string:
DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE; String formattedDate = formatter.format(LocalDate.now()); System.out.println(formattedDate);
As you can see, the DateTimeFormatter
has a few predefined instances you can use. In the example
above we use the DateTimeFormatter.BASIC_ISO_DATE
instance which is configured to parse and format
dates using the ISO date time format.
Tweet | |
Jakob Jenkov |