Sub topic 14
Formatting and Parsing with DateTimeFormatter
Dates in a program are objects. People read dates as text, such as "Nov 5, 2024" or "05/11/2024". So you need a way to turn a date into text, and to turn text back into a date.
- Formatting means turning a date or time object into a
String. - Parsing means reading a
Stringand building a date or time object from it.
Java handles both jobs with one class: DateTimeFormatter, from the package java.time.format. A formatter is a set of rules that says how a date looks as text.
The Default Format: ISO 8601
You have already seen dates print as 2024-11-05. That layout comes from ISO 8601, an international standard for writing dates and times. Every java.time type uses it by default.
toString()writes the ISO form.parse(text)with no formatter reads the ISO form.
import java.time.LocalDate;
import java.time.LocalDateTime;
public class IsoDefault {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("2024-11-05");
System.out.println(date); // 2024-11-05
LocalDateTime dt = LocalDateTime.parse("2024-11-05T14:07:09");
System.out.println(dt); // 2024-11-05T14:07:09
}
}The T separates the date from the time. Use ISO text when you store dates or send them between programs. It is clear, it sorts correctly as text, and every system can read it.
Built-In Formatters
DateTimeFormatter has ready-made formatters as constants. Here are a few:
| Constant | Example output |
|---|---|
| `ISO_LOCAL_DATE` | `2024-11-05` |
| `ISO_LOCAL_TIME` | `14:07:09` |
| `ISO_LOCAL_DATE_TIME` | `2024-11-05T14:07:09` |
| `ISO_DATE` | `2024-11-05` |
| `BASIC_ISO_DATE` | `20241105` |
You use them like this: date.format(DateTimeFormatter.BASIC_ISO_DATE).
Custom Patterns with ofPattern
Often you need a layout of your own, such as the day-first style used in much of Europe. DateTimeFormatter.ofPattern builds a formatter from a pattern. A pattern is a string where certain letters stand for parts of a date.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Formatting {
public static void main(String[] args) {
DateTimeFormatter input = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse("05/11/2024", input);
System.out.println(date); // 2024-11-05
DateTimeFormatter output = DateTimeFormatter.ofPattern("MMM d, yyyy", java.util.Locale.US);
System.out.println(date.format(output)); // Nov 5, 2024
}
}The first formatter reads day-first text. The second formatter writes the same date in a different style. The LocalDate stays the same. Only its text form changes.
Common Pattern Letters
The number of repeated letters matters. M gives 11, MM gives 11 (or 05 for May), MMM gives Nov, and MMMM gives November.
| Letter | Meaning | Example |
|---|---|---|
| `yyyy` | Year | `2024` |
| `MM` | Month number, two digits | `11` |
| `MMM` / `MMMM` | Month name, short / full | `Nov` / `November` |
| `dd` / `d` | Day of month, two digits / no padding | `05` / `5` |
| `EEE` / `EEEE` | Day of week, short / full | `Tue` / `Tuesday` |
| `HH` | Hour, 0 to 23 | `14` |
| `hh` | Hour, 1 to 12 | `02` |
| `a` | AM or PM | `PM` |
| `mm` | Minute | `07` |
| `ss` | Second | `09` |
| `VV` | Zone ID | `America/New_York` |
| `xxx` | Offset from UTC | `-05:00` |
Any letter in the range A to Z or a to z is reserved for these codes. If you want literal text in the output, put it in single quotes, for example "'Day' d". Symbols such as /, -, :, , and spaces print as they are.
Formatting Times and Zoned Values
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class TimePatterns {
public static void main(String[] args) {
LocalDateTime dt = LocalDateTime.of(2024, 11, 5, 14, 7, 9);
System.out.println(dt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
// 2024-11-05 14:07:09
System.out.println(dt.format(DateTimeFormatter.ofPattern("h:mm a", Locale.US)));
// 2:07 PM
System.out.println(dt.format(DateTimeFormatter.ofPattern("EEEE, MMMM d", Locale.US)));
// Tuesday, November 5
ZonedDateTime ny = dt.atZone(ZoneId.of("America/New_York"));
System.out.println(ny.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm xxx VV")));
// 2024-11-05 14:07 -05:00 America/New_York
}
}A pattern may only use fields that the object has. A LocalDate has no hour, so formatting it with HH throws an exception. A LocalDateTime has no zone, so VV throws too.
Locales: Names in the Reader's Language
A locale is a setting for a language and region, such as Locale.US or Locale.FRANCE. Month names, day names, and AM/PM text depend on the locale.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Locales {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 11, 5);
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("EEEE d MMMM yyyy", Locale.US);
System.out.println(date.format(pattern)); // Tuesday 5 November 2024
System.out.println(date.format(pattern.withLocale(Locale.FRANCE))); // mardi 5 novembre 2024
}
}Parsing Text into Dates
To parse, call the static parse method on the type you want and pass the formatter:
LocalDate.parse(text, formatter)LocalTime.parse(text, formatter)LocalDateTime.parse(text, formatter)
The text must match the pattern exactly. If it doesn't match, or if a value is impossible (for example, month 13), Java throws a DateTimeParseException. Input from users or files can be wrong, so catch this exception.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class SafeParse {
public static void main(String[] args) {
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String[] inputs = {"05/11/2024", "2024-11-05", "05/13/2024"};
for (String text : inputs) {
try {
System.out.println("OK: " + LocalDate.parse(text, f));
} catch (DateTimeParseException e) {
System.out.println("Could not parse: " + e.getParsedString());
}
}
}
}Output:
OK: 2024-11-05
Could not parse: 2024-11-05
Could not parse: 05/13/2024The type also has to fit the text. LocalDateTime.parse("05/11/2024", f) fails because the text has no time to read.
Common Mistakes
Mixing Up Similar Letters
Pattern letters are case-sensitive. These pairs cause most formatting bugs:
| Wrong | Right | Why |
|---|---|---|
| `mm` for month | `MM` | `mm` means minutes |
| `hh` in a 24-hour clock | `HH` | `hh` gives 1 to 12 |
| `YYYY` for year | `yyyy` | `YYYY` means week-based year |
| `DD` for day | `dd` | `DD` means day of the year |
The YYYY bug only shows up near New Year, so tests often miss it:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class WeekYearBug {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 12, 30);
System.out.println(date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.US))); // 2024-12-30
System.out.println(date.format(DateTimeFormatter.ofPattern("YYYY-MM-dd", Locale.US))); // 2025-12-30
}
}December 30, 2024 belongs to the first week of 2025 in US week numbering, so YYYY prints 2025.
Impossible Days Can Be Quietly Fixed
Formatters Are Safe to Share
DateTimeFormatter is immutable, which means it never changes after you create it. Methods like withLocale return a new formatter. Many threads can use the same formatter at once, so a common habit is to store it in a constant:
import java.time.format.DateTimeFormatter;
public class Formats {
public static final DateTimeFormatter DAY_FIRST = DateTimeFormatter.ofPattern("dd/MM/yyyy");
}The old SimpleDateFormat class could not be shared this way. That was one reason java.time replaced it.
Exercise
Write a pattern that formats LocalDateTime.of(2024, 3, 9, 18, 5) as "09.03.2024 18:05".
Show answer
Use DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm"). The dd and MM give two-digit day and month, HH gives the 24-hour hour, and mm gives minutes. The dots and space print as they are.
Exercise
A program formats a time with the pattern "hh:mm" and prints "02:30" for a meeting at 14:30. What is wrong, and how do you fix it?
Show answer
hh is the 12-hour clock, so 14 shows as 02. Use HH for 24-hour time ("HH:mm" prints "14:30"), or keep hh and add " a" with a locale, as in "hh:mm a" with Locale.US, to print "02:30 PM".
Exercise
What happens when you call LocalDate.parse("2024/11/05") with no formatter, and how do you parse that text correctly?
Show answer
It throws DateTimeParseException, because parse with no formatter expects ISO text like 2024-11-05. Pass a matching formatter: LocalDate.parse("2024/11/05", DateTimeFormatter.ofPattern("yyyy/MM/dd")).