Appearance
DateTimeFormatter
When using the old Date
object, we relied on SimpleDateFormat
for formatting and displaying dates. With the new LocalDateTime
or ZonedDateTime
, we use DateTimeFormatter
for formatting.
Unlike SimpleDateFormat
, DateTimeFormatter
is an immutable object and is thread-safe. The concept of threads will be discussed later, but for now, remember that since SimpleDateFormat
is not thread-safe, you must create a new local variable each time you use it. In contrast, you can create a single instance of DateTimeFormatter
and use it throughout your code.
You create a DateTimeFormatter
by passing a formatting string:
java
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
The usage of the formatting string is identical to that of SimpleDateFormat
.
Another way to create a DateTimeFormatter
is by passing a formatting string while specifying a Locale
:
java
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, yyyy-MMMM-dd HH:mm", Locale.US);
This approach formats according to the default habits of the specified locale. Here’s an example:
java
import java.time.*;
import java.time.format.*;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.now();
var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm ZZZZ");
System.out.println(formatter.format(zdt));
var zhFormatter = DateTimeFormatter.ofPattern("yyyy MMM dd EE HH:mm", Locale.CHINA);
System.out.println(zhFormatter.format(zdt));
var usFormatter = DateTimeFormatter.ofPattern("E, MMMM/dd/yyyy HH:mm", Locale.US);
System.out.println(usFormatter.format(zdt));
}
}
In the formatting string, if you need to output fixed characters, you can use 'xxx'
to denote them.
When you run the above code, you will see the current time displayed in different formats based on the locale:
2019-09-15T23:16 GMT+08:00
2019 9月 15 周日 23:16
Sun, September/15/2019 23:16
When you directly call System.out.println()
on a ZonedDateTime
or LocalDateTime
instance, it actually invokes their toString()
method, which formats the output according to ISO 8601 by default. You can also use the pre-defined static variables of DateTimeFormatter
for this purpose:
java
var ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ISO_DATE.format(ldt));
System.out.println(DateTimeFormatter.ISO_DATE_TIME.format(ldt));
The output will be similar to that of toString()
:
2019-09-15
2019-09-15T23:16:51.56217
Summary
To format ZonedDateTime
or LocalDateTime
, you need to use the DateTimeFormatter
class.
DateTimeFormatter
allows for custom output of dates and times using formatting strings and Locale
.