Learn to format a given date to a specified formatted string in Java. We will learn to use inbuilt patterns and custom patterns with DateTimeFormatter and SimpleDateFormat.
1. Formatting with DateTimeFormatter [Java 8]
Since Java 8, We can use DateTimeFormatter for all types of date and time related formatting tasks. This class is thread-safe and immutable so can be used in concurrent environments without risks.
To format a date instance to string, we first need to create DateTimeFormatter instance with desired output pattern and then use its format()
method to format the date.
1.1. Creating DateTimeFormatter
We can create DateTimeFormatter
in three ways:
- Using inbuilt patterns
- Using custom patterns using
ofPattern()
method - Using localized styles with
FormatStyle
, such as long or medium
//Use inbuilt pattern constants
DateTimeFormatter inBuiltFormatter1 = DateTimeFormatter.ISO_DATE_TIME;
DateTimeFormatter inBuiltFormatter2 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//Define your own custom patterns
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mma z");
//Using FormatStyle
DateTimeFormatter customFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
Read More: DateTimeFormatter class
1.2. Formatting ZonedDateTime, LocalDateTime and LocalDate
The DateTimeFormatter class provides the methods String format(TemporalAccessor temporal)
that can be used to format ZonedDateTime
, LocalDateTime
and LocalDate
instances.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class FormattingDates {
public static final String ZDT_PATTERN = "yyyy-MM-dd HH:mm:ss a z";
public static final DateTimeFormatter ZDT_FORMATTER
= DateTimeFormatter.ofPattern(ZDT_PATTERN);
public static final String LDT_PATTERN = "yyyy-MM-dd HH:mm:ss a";
public static final DateTimeFormatter LDT_FORMATTER
= DateTimeFormatter.ofPattern(LDT_PATTERN);
public static final String LD_PATTERN = "yyyy-MM-dd";
public static final DateTimeFormatter LD_FORMATTER
= DateTimeFormatter.ofPattern(LD_PATTERN);
public static void main(String[] args) {
String instanceString = ZDT_FORMATTER.format(ZonedDateTime.now());
System.out.println(instanceString);
String dateTimeString = LDT_FORMATTER.format(LocalDateTime.now());
System.out.println(dateTimeString);
String dateString = LD_FORMATTER.format(LocalDate.now());
System.out.println(dateString);
}
}
1.2. Creating Custom Patterns
The custom pattern string can have any number of pre-defined letters and symbols which have their own meaning. The most used symbols are : Y, M, D, h, m, and s
.
Also, note that the number of repetitions of a letter in the pattern also have different meanings. For example, “MMM”
gives “Jan,”
whereas “MMMM”
gives “January.”
Let’s see these symbols for quick reference.
Symbol | Meaning | Type | Example |
---|---|---|---|
G | Era | String | AD; Anno Domini |
y | Year of era | Year | 2004 or 04 |
u | Year of era | Year | Similar to ‘y’ but returns proleptic year. |
D | Day of year | Number | 235 |
M / L | Month of year | Number / String | 7 or 07; J or Jul or July |
d | Day of month | Number | 21 |
Q / q | Quarter of year | Number / String | 3 or 03; Q3 or 3rd quarter |
Y | Week based year | Year | 1996 or 96 |
w | Week of week based year | Number | 32 |
W | Week of month | Number | 3 |
e / c | Localized day of week | Number / String | 2 or 02; T or Tue or Tuesday |
E | Day of week | String | T or Tue or Tuesday |
F | Week of month | Number | 3 |
a | am / pm of the day | String | PM |
h | Clock hour of am pm (1-12) | Number | 12 |
K | Hour of am pm (0-11) | Number | 0 |
k | Clock hour of am pm (1-24) | Number | 15 |
H | Hour of day (0-23) | Number | 15 |
m | Minute of hour | Number | 30 |
s | Second of minute | Number | 55 |
S | Fraction of second | Fraction | 978 |
A | Millisecond of day | Number | 1234 |
n | Nanosecond of second | Number | 987654321 |
N | Nanosecond of day | Number | 1234560000 |
V | Time zone ID | Zone-id | America/Los_Angeles or Z or –08:30 |
z | Time zone name | Zone-name | Pacific Standard Time or PST |
X | Zone offset Z for zero | Offset-X | Z or –08 or –0830 or –08:30 or –083015 or –08:30:15 |
x | Zone offset | Offset-x | +0000 or –08 or –0830 or –08:30 or –083015 or –08:30:15 |
Z | Zone offset | Offset-Z | +0000 or –0800 or –08:00 |
O | Localized zone offset | Offset-O | GMT+8 or GMT+08:00 or UTC–08:00 |
p | Pad next | Pad modifier | 1 |
1.4. UnsupportedTemporalTypeException
If we try to use DateTimeFormatter
with pattern that is not supported by the date-time instance, its format()
will throw this exception.
For example, if we try to format LocalDate
with pattern containing hours and minutes then this exception will be thrown, because LocalDate
does not support any time information.
public static final String TIMESTAMP_PATTERN
= "yyyy-MM-dd HH:mm:ss a";
public static final DateTimeFormatter FOMATTER
= DateTimeFormatter.ofPattern(TIMESTAMP_PATTERN);
String formmatedString = FOMATTER.format( LocalDate.now() );
Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
at java.base/java.time.LocalDate.get0(LocalDate.java:709)
at java.base/java.time.LocalDate.getLong(LocalDate.java:688)
...
2. Formatting with SimpleDateFormat [Java 7]
In case you are still stuck at Java 7 and can’t upgrade due to some legacy application’s dependencies, you can use SimpleDateFormat
for date formatting in a locale-sensitive manner.
Though SimpleDateFormat
is not thread-safe or immutable, still, it serves the purpose pretty well. Do not use this class in a multi-threaded environment without added synchronization.
2.1. Creating SimpleDateFormat
SimpleDateFormat provides the following constructors:
SimpleDateFormat(pattern)
: uses the given pattern and the default date format symbols for the default locale.SimpleDateFormat(pattern, locale)
: uses the given pattern and the default date format symbols for the given locale.SimpleDateFormat(pattern, formatSymbols)
: uses the given pattern and date format symbols.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat simpleDateFormat =new SimpleDateFormat("MM-dd-yyyy", new Locale("fr", "FR"));
DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
symbols.setAmPmStrings(new String[] { "AM", "PM" }); //Override specific symbols and retaining others
sdf.setDateFormatSymbols(symbols);
2.2. Convert Date to String
Now we can use the constructed SimpleDateFormat instance to format a given Date object to a string.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String formattedDate = sdf.format(new Date());
System.out.println(formattedDate);
String pattern = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ";
SimpleDateFormat sdfWithLocale =new SimpleDateFormat(pattern,
new Locale("fr", "FR"));
String date = sdfWithLocale.format(new Date());
System.out.println(date);
DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
symbols.setAmPmStrings(new String[] { "AM", "PM" });
sdf.setDateFormatSymbols(symbols);
formattedDate = sdf.format(new Date());
System.out.println(formattedDate);
Program Output.
2022-02-17 21:57:01 pm
jeudi février 2022 21:57:01.644+0530
2022-02-17 21:57:01 PM
3. Conclusion
If you have the liberty to upgrade a Java 7 application to the latest Java version, please do it on priority. The thread-safe and immutable nature of DateTimeFormatter
is a huge win in terms of performance over SimpleDateFormat
.
Both classes provide format()
example which is used to format the date objects into a string.
Happy Learning !!