Formatting and Parsing Dates in Java, and Converting Legacy Date and Calendar
Turning java.time values into text and back: the predefined ISO formatters, localized styles and skeleton patterns, custom pattern letters and their traps (Y vs y, m vs M), resolver styles, DateTimeFormatterBuilder, and converting to and from Date, Calendar, TimeZone and java.sql types.
kvi5hnuCode Sprout team member14 min readOn this page
The last three articles built up the java.time value classes. Sooner or later every one of those values has to leave the program as text (a log line, a JSON field, a label on screen) or come in from text (a form, a file, an HTTP header). That is the job of java.time.format.DateTimeFormatter. This article covers its three flavours (predefined, localized and pattern based), parsing and validation, the builder for unusual formats, and finally the bridge methods that connect java.time with the older Date, Calendar and java.sql classes you will still meet in existing code.
One formatter class, three ways to get one
A DateTimeFormatter is an immutable, thread-safe object that knows how to print and parse. You obtain one in one of three ways:
| Kind | How you get it | Typical use |
|---|---|---|
| Predefined | constants such as DateTimeFormatter.ISO_LOCAL_DATE | machine-readable timestamps, data exchange |
| Localized | ofLocalizedDate(FormatStyle), ofLocalizedPattern("yMMMd") | text shown to people, adapted to their locale |
| Pattern | ofPattern("dd.MM.uuuu") | a fixed, externally imposed layout |
You print either with formatter.format(value) or with value.format(formatter); both do the same thing. You parse with the static parse method of the target class, for example LocalDate.parse(text, formatter).
The predefined formatters
The constants on DateTimeFormatter cover the ISO 8601 family plus one email/HTTP format. Each value below is the Apollo 11 launch, 1969-07-16 09 in New York:
| Constant | Output | Notes |
|---|---|---|
ISO_LOCAL_DATE | 1969-07-16 | also ISO_LOCAL_TIME, ISO_LOCAL_DATE_TIME (separator T) |
ISO_OFFSET_DATE_TIME | 1969-07-16T09:32:00-04:00 | also ISO_OFFSET_DATE, ISO_OFFSET_TIME |
ISO_ZONED_DATE_TIME | 1969-07-16T09:32:00-04:00[America/New_York] | offset plus region ID in brackets |
ISO_INSTANT | 1969-07-16T13:32:00Z | always printed in UTC |
ISO_DATE, ISO_TIME, ISO_DATE_TIME | as above | zone information printed if present, optional when parsing |
BASIC_ISO_DATE | 19690716-0400 | no separators |
ISO_ORDINAL_DATE | 1969-197-04:00 | year and day of year |
ISO_WEEK_DATE | 1969-W29-3-04:00 | week-based year, week, day of week |
RFC_1123_DATE_TIME | Wed, 16 Jul 1969 09:32:00 -0400 | email and HTTP headers, always English |
The toString methods of the value classes produce ISO output already, and their one-argument parse methods accept it, so LocalDate.parse("1903-06-14") needs no formatter at all. Use the explicit constants when you need a variant that toString does not produce, such as ISO_INSTANT for a ZonedDateTime.
Localized styles
Text for humans should follow the reader's conventions. ofLocalizedDate, ofLocalizedTime and ofLocalizedDateTime take a FormatStyle (SHORT, MEDIUM, LONG, FULL), and ofLocalizedDateTime(dateStyle, timeStyle) lets the two halves differ. The locale comes from the default (Locale.getDefault(Locale.Category.FORMAT)) unless you call withLocale:
| Style | en-US | de-DE | ja-JP |
|---|---|---|---|
SHORT | 7/16/69 | 16.07.69 | 1969/07/16 |
MEDIUM | Jul 16, 1969 | 16.07.1969 | 1969/07/16 |
LONG | July 16, 1969 | 16. Juli 1969 | 1969年7月16日 |
FULL | Wednesday, July 16, 1969 | Mittwoch, 16. Juli 1969 | 1969年7月16日水曜日 |
The text comes from the Unicode CLDR data that the JDK uses by default since Java 9, and CLDR is updated in almost every JDK release. Treat localized output as display-only: never store it, compare it in tests across JDK versions, or parse it back as a data format.
There are two other knobs. localizedBy(Locale) (Java 10) also honours Unicode extensions in the locale: ja-JP-u-ca-japanese switches the calendar to the Japanese imperial era (昭和44年7月16日), and ar-EG with localizedBy uses Arabic-Indic digits, while withLocale keeps the chronology and digits of the formatter. withDecimalStyle controls the digits and signs directly.
Skeleton patterns with ofLocalizedPattern
Sometimes none of the four styles fits: you want "month abbreviation, day and year" but in each locale's own order and punctuation. Java 19 added ofLocalizedPattern(String requestedTemplate). You list the fields you want, from largest to smallest and without separators, and CLDR supplies the best local arrangement:
| Template | en-US | en-GB | de-DE | zh-CN |
|---|---|---|---|---|
yMMMd | Jul 16, 1969 | 16 Jul 1969 | 16. Juli 1969 | 1969年7月16日 |
For hours, the letter j means "the locale's preferred hour cycle": jm prints 11:59 PM in the US and 23:59 in Germany. The template has a fixed grammar: the letters must appear in the order G y Q M w E d B (h|H|j|C) m s (v|z), each one optional. Anything else, such as dMy or a quarter placed after the day, throws IllegalArgumentException ("Requested template is invalid") as soon as you call ofLocalizedPattern.
Names of days and months
DayOfWeek and Month have getDisplayName(TextStyle, Locale). TextStyle offers FULL, SHORT and NARROW plus _STANDALONE variants, which matter in languages where a month name on its own is spelled differently from one inside a date (Russian and Polish, for example):
Month.MARCH.getDisplayName(TextStyle.FULL, Locale.GERMAN) // März
DayOfWeek.WEDNESDAY.getDisplayName(TextStyle.SHORT, Locale.ENGLISH) // Wed
Custom patterns
ofPattern("EEE yyyy-MM-dd HH:mm") builds a formatter from pattern letters. Each letter selects a field, and the number of repetitions selects the form: generally 1 or 2 for numbers (with or without padding), 3 for an abbreviation, 4 for the full name and 5 for the narrow form. Text in single quotes is literal; '' is a single quote.
| Letter | Field | Examples (1969-07-16 09 New York) |
|---|---|---|
G | era | G AD, GGGG Anno Domini |
u | proleptic year (may be negative) | uuuu 1969, uu 69 |
y | year of era (always positive) | yyyy 1969, yy 69 |
Y | week-based year | see the trap below |
M / L | month (L is standalone) | M 7, MM 07, MMM Jul, MMMM July, MMMMM J |
d | day of month | d 16, dd 16 |
D | day of year | D 197 |
Q | quarter | Q 3, QQQ Q3 |
w | week of week-based year | w 29 |
E / e | day of week (e is localized number) | E Wed, EEEE Wednesday |
a | AM/PM | a AM |
B | period of day (Java 16) | B in the morning, at night |
H, h, k, K | hour 0-23, 1-12, 1-24, 0-11 | HH 09, h 9 |
m, s | minute, second | mm 32, ss 00 |
S, n | fraction of second, nano of second | SSS 000, n 0 |
VV | zone ID | America/New_York |
z, v | zone name, generic zone name | z EDT, zzzz Eastern Daylight Time, v ET |
O | localized offset | O GMT-4 |
X, x, Z | offset (X prints Z for zero) | x -04, xx -0400, xxx -04 |
ofPattern(pattern) uses the default locale for names like Wed, so pass a locale explicitly when the output must be stable: ofPattern("EEE d MMM", Locale.US).
Parsing
Every value class has a static parse(CharSequence) for ISO text and parse(CharSequence, DateTimeFormatter) for anything else:
LocalDate birthday = LocalDate.parse("1903-06-14");
ZonedDateTime launch = ZonedDateTime.parse("1969-07-16 03:32:00-0400",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxx"));
On failure you get a DateTimeParseException (unchecked), which reports the offending text with getParsedString() and the position where parsing stopped with getErrorIndex(). Parsing 1969/07/16 as an ISO date fails at index 4, the first slash.
The text must contain enough information for the target type. A ZonedDateTime needs a zone or offset; a LocalDate needs year, month and day. For partial data, call formatter.parse(text) to get a raw TemporalAccessor and query it, for example MonthDay.from(formatter.parse("07/16")). When the input may or may not include a zone, parseBest(text, ZonedDateTime::from, LocalDateTime::from) returns the first type that succeeds.
Resolver styles: how strict is strict?
After the text is split into fields, a resolver combines them into a value. ResolverStyle has three settings:
| Style | 2023-02-30 with uuuu-MM-dd | Behaviour |
|---|---|---|
SMART (default for ofPattern) | 2023-02-28 | clamps day-of-month 29 to 31 to the end of the month, rejects 32 |
LENIENT | 2023-03-02 | rolls overflow into the next fields |
STRICT (used by the ISO constants) | rejected | the date must exist exactly |
For validating user input, use withResolverStyle(ResolverStyle.STRICT). There is a well-known catch: in strict mode the pattern letter y means year of era, and without an era field (G) the resolver cannot turn it into a proleptic year, so yyyy-MM-dd rejects even valid dates. Use uuuu together with STRICT.
DateTimeFormatterBuilder
Patterns cover most needs. When they don't, DateTimeFormatterBuilder assembles a formatter from parts:
DateTimeFormatter flexible = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("uuuu-MM-dd")
.optionalStart()
.appendLiteral('T').append(DateTimeFormatter.ISO_LOCAL_TIME)
.optionalEnd()
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter(Locale.ROOT);
This accepts both 2025-03-01 and 2025-03-01T14:05:30 as a LocalDateTime, filling in midnight when the time is missing. Other useful builder methods:
appendValue(field, width)andappendValue(field, min, max, SignStyle)for numbers, including fields such asIsoFields.QUARTER_OF_YEAR.appendText(field, Map<Long,String>)for your own names (two-letter weekday codes, say).appendFraction(NANO_OF_SECOND, 0, 9, true)for a variable-length fraction.appendOffset("+HH:MM", "Z"),appendZoneId(),appendInstant(digits).appendDayPeriodText(TextStyle)(Java 16) for "in the morning" and similar.parseStrict()/parseLenient()andparseCaseSensitive()/parseCaseInsensitive()toggles that apply to everything appended after them.optionalStart()/optionalEnd()for parts that may be missing in the input.
The static helper DateTimeFormatterBuilder.getLocalizedDateTimePattern (with styles, and a requestedTemplate overload since Java 19) shows the pattern behind a localized formatter, which is handy for debugging.
Converting to and from the legacy classes
java.time arrived in Java 8, and a great deal of code (and many libraries) still use java.util.Date, java.util.Calendar, java.util.TimeZone and the java.sql types. Rather than adding conversion methods to the new classes, Java 8 added them to the old ones:

| Legacy | java.time | To java.time | From java.time |
|---|---|---|---|
java.util.Date | Instant | date.toInstant() | Date.from(instant) |
GregorianCalendar | ZonedDateTime | cal.toZonedDateTime() | GregorianCalendar.from(zdt) |
TimeZone | ZoneId | tz.toZoneId() | TimeZone.getTimeZone(zoneId) |
java.sql.Date | LocalDate | d.toLocalDate() | java.sql.Date.valueOf(localDate) |
java.sql.Time | LocalTime | t.toLocalTime() | java.sql.Time.valueOf(localTime) |
java.sql.Timestamp | LocalDateTime | ts.toLocalDateTime() | Timestamp.valueOf(localDateTime) |
java.sql.Timestamp | Instant | ts.toInstant() | Timestamp.from(instant) |
java.text.Format | DateTimeFormatter | (none) | formatter.toFormat() |
java.nio.file.attribute.FileTime | Instant | ft.toInstant() | FileTime.from(instant) |
A few details are worth knowing:
Datehas millisecond precision, soDate.from(instant)drops nanoseconds. It throwsIllegalArgumentExceptionfor instants too far from 1970 to fit alongof milliseconds.- A plain
Calendarreference may hold a non-Gregorian calendar (for example a Thai Buddhist one); checkinstanceof GregorianCalendarbefore callingtoZonedDateTime, or go throughcal.toInstant()and a zone. java.sql.Dateandjava.sql.Timeextendjava.util.Datebut have no meaningful instant; their inheritedtoInstant()throwsUnsupportedOperationException. Always usetoLocalDate()andtoLocalTime().Timestampkeeps full nanoseconds, soTimestamp.valueOf(LocalDateTime)andtoLocalDateTime()round-trip exactly.- With JDBC 4.2 drivers you rarely need the
java.sqltypes at all:rs.getObject(col, LocalDate.class)andps.setObject(i, localDate)work directly, as article 59 showed. toFormat()andtoFormat(TemporalQuery)produce ajava.text.Formatfor APIs that insist on one, such asMessageFormator old Swing formatted fields. The query variant decides whatparseObjectreturns, for example aLocalDate.
The program
The demo runs through everything above with fixed values and explicit locales, so the output does not depend on the machine it runs on. The narrow no-break space in the US time is made visible as <NNBSP>.
import java.text.Format;
import java.text.ParsePosition;
import java.time.*;
import java.time.format.*;
import java.time.temporal.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
ZonedDateTime launch = ZonedDateTime.of(1969, 7, 16, 9, 32, 0, 0,
ZoneId.of("America/New_York"));
System.out.println("== Predefined ISO formatters ==");
System.out.println("ISO_LOCAL_DATE " + DateTimeFormatter.ISO_LOCAL_DATE.format(launch));
System.out.println("ISO_OFFSET_DATE_TIME " + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(launch));
System.out.println("ISO_ZONED_DATE_TIME " + DateTimeFormatter.ISO_ZONED_DATE_TIME.format(launch));
System.out.println("ISO_INSTANT " + DateTimeFormatter.ISO_INSTANT.format(launch));
System.out.println("BASIC_ISO_DATE " + DateTimeFormatter.BASIC_ISO_DATE.format(launch));
System.out.println("ISO_ORDINAL_DATE " + DateTimeFormatter.ISO_ORDINAL_DATE.format(launch));
System.out.println("ISO_WEEK_DATE " + DateTimeFormatter.ISO_WEEK_DATE.format(launch));
System.out.println("RFC_1123_DATE_TIME " + DateTimeFormatter.RFC_1123_DATE_TIME.format(launch));
System.out.println("\n== Localized styles ==");
for (FormatStyle style : FormatStyle.values()) {
for (Locale loc : List.of(Locale.US, Locale.GERMANY, Locale.JAPAN)) {
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate(style).withLocale(loc);
System.out.printf("%-6s %-6s %s%n", style, loc, f.format(launch));
}
}
DateTimeFormatter longDt = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG).withLocale(Locale.FRANCE);
System.out.println("LONG date-time, fr_FR: " + longDt.format(launch));
try {
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.US).format(launch.toLocalDateTime());
} catch (DateTimeException e) {
System.out.println("LONG needs a zone: " + e.getClass().getSimpleName());
}
System.out.println("\n== Localized patterns (skeletons) ==");
DateTimeFormatter skel = DateTimeFormatter.ofLocalizedPattern("yMMMd");
for (Locale loc : List.of(Locale.US, Locale.UK, Locale.GERMANY, Locale.CHINA))
System.out.println("yMMMd " + loc + ": " + skel.withLocale(loc).format(launch));
DateTimeFormatter hm = DateTimeFormatter.ofLocalizedPattern("jm");
for (Locale loc : List.of(Locale.US, Locale.GERMANY))
System.out.println("jm " + loc + ": "
+ visible(hm.withLocale(loc).format(LocalTime.of(23, 59))));
System.out.println("\n== Display names ==");
StringBuilder days = new StringBuilder();
for (DayOfWeek d : DayOfWeek.values())
days.append(d.getDisplayName(TextStyle.SHORT, Locale.ENGLISH)).append(' ');
System.out.println(days.toString().strip());
System.out.println(Month.MARCH.getDisplayName(TextStyle.FULL, Locale.GERMAN)
+ " / " + Month.MARCH.getDisplayName(TextStyle.FULL, Locale.FRENCH)
+ " / " + Month.MARCH.getDisplayName(TextStyle.NARROW, Locale.ENGLISH));
System.out.println("\n== Custom patterns ==");
DateTimeFormatter custom = DateTimeFormatter.ofPattern("EEE yyyy-MM-dd HH:mm", Locale.US);
System.out.println(custom.format(launch));
System.out.println(DateTimeFormatter.ofPattern("EEEE d MMMM uuuu, h:mm a zzzz", Locale.US).format(launch));
System.out.println(DateTimeFormatter.ofPattern("VV xxx '(week' w')'", Locale.US).format(launch));
System.out.println("B at 21:00: " + DateTimeFormatter.ofPattern("h B", Locale.US)
.format(LocalTime.of(21, 0)));
System.out.println("\n== The Y vs y trap ==");
LocalDate dec30 = LocalDate.of(2024, 12, 30);
System.out.println("yyyy-MM-dd: " + DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.US).format(dec30));
System.out.println("YYYY-MM-dd: " + DateTimeFormatter.ofPattern("YYYY-MM-dd", Locale.US).format(dec30));
System.out.println("mm vs MM : " + DateTimeFormatter.ofPattern("yyyy-mm-dd", Locale.US)
.format(LocalDateTime.of(2024, 12, 30, 8, 5)));
System.out.println("\n== Parsing ==");
System.out.println(LocalDate.parse("1903-06-14"));
ZonedDateTime parsed = ZonedDateTime.parse("1969-07-16 03:32:00-0400",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxx"));
System.out.println(parsed);
System.out.println(LocalDate.parse("16 Jul 1969", DateTimeFormatter.ofPattern("d MMM uuuu", Locale.US)));
try {
LocalDate.parse("1969/07/16");
} catch (DateTimeParseException e) {
System.out.println("parse error at index " + e.getErrorIndex() + ": " + e.getParsedString());
}
DateTimeFormatter smart = DateTimeFormatter.ofPattern("uuuu-MM-dd");
DateTimeFormatter lenient = smart.withResolverStyle(ResolverStyle.LENIENT);
DateTimeFormatter strict = smart.withResolverStyle(ResolverStyle.STRICT);
System.out.println("SMART 2023-02-30 -> " + LocalDate.parse("2023-02-30", smart));
System.out.println("LENIENT 2023-02-30 -> " + LocalDate.parse("2023-02-30", lenient));
try {
LocalDate.parse("2023-02-30", strict);
} catch (DateTimeParseException e) {
System.out.println("STRICT 2023-02-30 -> rejected");
}
try {
LocalDate.parse("2023-02-28", DateTimeFormatter.ofPattern("yyyy-MM-dd")
.withResolverStyle(ResolverStyle.STRICT));
} catch (DateTimeParseException e) {
System.out.println("STRICT with yyyy and no era -> rejected");
}
TemporalAccessor raw = DateTimeFormatter.ofPattern("MM/dd").parse("07/16");
System.out.println("MonthDay from partial parse: " + MonthDay.from(raw));
System.out.println("parseBest: " + DateTimeFormatter.ISO_DATE_TIME
.parseBest("1969-07-16T09:32", ZonedDateTime::from, LocalDateTime::from));
System.out.println("\n== DateTimeFormatterBuilder ==");
DateTimeFormatter flexible = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("uuuu-MM-dd")
.optionalStart().appendLiteral('T').append(DateTimeFormatter.ISO_LOCAL_TIME).optionalEnd()
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter(Locale.ROOT);
System.out.println(LocalDateTime.parse("2025-03-01", flexible));
System.out.println(LocalDateTime.parse("2025-03-01T14:05:30", flexible));
DateTimeFormatter quarter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4).appendLiteral("-Q")
.appendValue(IsoFields.QUARTER_OF_YEAR).toFormatter();
System.out.println("Quarter: " + quarter.format(launch));
DateTimeFormatter dayCount = new DateTimeFormatterBuilder()
.appendText(ChronoField.DAY_OF_WEEK, Map.of(1L, "Mo", 2L, "Tu", 3L, "We",
4L, "Th", 5L, "Fr", 6L, "Sa", 7L, "Su"))
.appendLiteral(' ').appendValue(ChronoField.DAY_OF_MONTH).toFormatter();
System.out.println("Custom text: " + dayCount.format(launch));
System.out.println("\n== Legacy interop ==");
Instant moment = launch.toInstant();
Date legacyDate = Date.from(moment);
System.out.println("Date.getTime(): " + legacyDate.getTime());
System.out.println("back to Instant: " + legacyDate.toInstant());
GregorianCalendar cal = GregorianCalendar.from(launch);
System.out.println("Calendar zone: " + cal.getTimeZone().getID()
+ ", hour " + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("back: " + cal.toZonedDateTime());
TimeZone tz = TimeZone.getTimeZone("Asia/Kolkata");
System.out.println("TimeZone -> ZoneId: " + tz.toZoneId()
+ ", ZoneId -> TimeZone: " + TimeZone.getTimeZone(ZoneId.of("Europe/Paris")).getID());
java.sql.Date sqlDate = java.sql.Date.valueOf(LocalDate.of(1969, 7, 16));
java.sql.Time sqlTime = java.sql.Time.valueOf(LocalTime.of(9, 32));
java.sql.Timestamp ts = java.sql.Timestamp.valueOf(LocalDateTime.of(1969, 7, 16, 9, 32, 0, 123456789));
System.out.println("sql: " + sqlDate.toLocalDate() + " " + sqlTime.toLocalTime()
+ " " + ts.toLocalDateTime() + " nanos=" + ts.getNanos());
try {
sqlDate.toInstant();
} catch (UnsupportedOperationException e) {
System.out.println("java.sql.Date.toInstant() -> UnsupportedOperationException");
}
Format legacyFormat = DateTimeFormatter.ISO_LOCAL_DATE.toFormat();
System.out.println("toFormat(): " + legacyFormat.format(LocalDate.of(1969, 7, 16)));
Object back = DateTimeFormatter.ISO_LOCAL_DATE.toFormat(LocalDate::from)
.parseObject("2001-09-09", new ParsePosition(0));
System.out.println("toFormat(query) parsed a " + back.getClass().getSimpleName() + ": " + back);
}
static String visible(String s) {
return s.replace("\u202f", "<NNBSP>");
}
}
== Predefined ISO formatters ==
ISO_LOCAL_DATE 1969-07-16
ISO_OFFSET_DATE_TIME 1969-07-16T09:32:00-04:00
ISO_ZONED_DATE_TIME 1969-07-16T09:32:00-04:00[America/New_York]
ISO_INSTANT 1969-07-16T13:32:00Z
BASIC_ISO_DATE 19690716-0400
ISO_ORDINAL_DATE 1969-197-04:00
ISO_WEEK_DATE 1969-W29-3-04:00
RFC_1123_DATE_TIME Wed, 16 Jul 1969 09:32:00 -0400
== Localized styles ==
FULL en_US Wednesday, July 16, 1969
FULL de_DE Mittwoch, 16. Juli 1969
FULL ja_JP 1969年7月16日水曜日
LONG en_US July 16, 1969
LONG de_DE 16. Juli 1969
LONG ja_JP 1969年7月16日
MEDIUM en_US Jul 16, 1969
MEDIUM de_DE 16.07.1969
MEDIUM ja_JP 1969/07/16
SHORT en_US 7/16/69
SHORT de_DE 16.07.69
SHORT ja_JP 1969/07/16
LONG date-time, fr_FR: 16 juillet 1969, 09:32:00 EDT
LONG needs a zone: DateTimeException
== Localized patterns (skeletons) ==
yMMMd en_US: Jul 16, 1969
yMMMd en_GB: 16 Jul 1969
yMMMd de_DE: 16. Juli 1969
yMMMd zh_CN: 1969年7月16日
jm en_US: 11:59<NNBSP>PM
jm de_DE: 23:59
== Display names ==
Mon Tue Wed Thu Fri Sat Sun
März / mars / M
== Custom patterns ==
Wed 1969-07-16 09:32
Wednesday 16 July 1969, 9:32 AM Eastern Daylight Time
America/New_York -04:00 (week 29)
B at 21:00: 9 at night
== The Y vs y trap ==
yyyy-MM-dd: 2024-12-30
YYYY-MM-dd: 2025-12-30
mm vs MM : 2024-05-30
== Parsing ==
1903-06-14
1969-07-16T03:32-04:00
1969-07-16
parse error at index 4: 1969/07/16
SMART 2023-02-30 -> 2023-02-28
LENIENT 2023-02-30 -> 2023-03-02
STRICT 2023-02-30 -> rejected
STRICT with yyyy and no era -> rejected
MonthDay from partial parse: --07-16
parseBest: 1969-07-16T09:32
== DateTimeFormatterBuilder ==
2025-03-01T00:00
2025-03-01T14:05:30
Quarter: 1969-Q3
Custom text: We 16
== Legacy interop ==
Date.getTime(): -14552880000
back to Instant: 1969-07-16T13:32:00Z
Calendar zone: America/New_York, hour 9
back: 1969-07-16T09:32-04:00[America/New_York]
TimeZone -> ZoneId: Asia/Kolkata, ZoneId -> TimeZone: Europe/Paris
sql: 1969-07-16 09:32 1969-07-16T09:32:00.123456789 nanos=123456789
java.sql.Date.toInstant() -> UnsupportedOperationException
toFormat(): 1969-07-16
toFormat(query) parsed a LocalDate: 2001-09-09
Common questions
Why does my parser accept February 30 or February 29 in a non-leap year?
ofPattern formatters use the SMART resolver, which clamps the day of month to the end of the month. 2026-02-29 parses as 2026-02-28 without error. Use withResolverStyle(ResolverStyle.STRICT) and the year letter uuuu.
What's the difference between yyyy, uuuu and YYYY?
yyyy is year of era (always positive, combined with G for BC/AD), uuuu is the proleptic year (can be zero or negative), and YYYY is the week-based year, which differs at the turn of the year. For ordinary dates, uuuu or yyyy give the same output; with STRICT, only uuuu works without an era.
How do I parse a date with a month name like "Mar"?
ofPattern("d MMM uuuu", Locale.ENGLISH). Without the locale, the default locale's names are expected, and parsing fails on a German or French machine. Parsing is case-sensitive by default; use DateTimeFormatterBuilder().parseCaseInsensitive() for "MAR".
How do I accept several formats?
Use optional sections ([...]) in one pattern, or try a list of formatters in order and return the first successful parse. Optional sections also work for formatting: appendOptional, or [...] in patterns.
Can I still use SimpleDateFormat?
Only when maintaining code that requires Date. It is mutable and not thread-safe, it uses lenient parsing by default, and its patterns differ slightly from DateTimeFormatter. Convert at the boundary with toInstant() and Date.from().
How do I convert a java.util.Date to LocalDate?
LocalDate.ofInstant(date.toInstant(), zone) (Java 9) with an explicit zone, since a Date is a moment and the calendar date depends on where you are. For a java.sql.Date, call toLocalDate() directly; its toInstant() throws.
API reference
| Method | Purpose |
|---|---|
DateTimeFormatter.ISO_*, BASIC_ISO_DATE, RFC_1123_DATE_TIME | predefined formatters |
ofLocalizedDate/Time/DateTime(FormatStyle) | locale-dependent styles |
ofLocalizedPattern(String) (19) | locale-dependent layout for a set of fields |
ofPattern(String), ofPattern(String, Locale) | custom pattern |
withLocale, localizedBy (10), withZone, withDecimalStyle, withResolverStyle | derived formatters |
format(TemporalAccessor), formatTo(TemporalAccessor, Appendable) | |
parse(CharSequence), parse(CharSequence, TemporalQuery), parseBest | parse to raw fields or a type |
LocalDate.parse(text[, formatter]) and friends | parse to a value class |
DateTimeParseException.getErrorIndex(), getParsedString() | error details |
toFormat(), toFormat(TemporalQuery) | adapter to java.text.Format |
DayOfWeek/Month.getDisplayName(TextStyle, Locale) | localized names |
DateTimeFormatterBuilder | build formatters from parts |
Date.from, toInstant; GregorianCalendar.from, toZonedDateTime; TimeZone.toZoneId, getTimeZone(ZoneId) | legacy interop |
java.sql.Date/Time/Timestamp.valueOf, toLocalDate/Time/DateTime, Timestamp.from, toInstant | SQL interop |
Summary
DateTimeFormatteris immutable and thread-safe; keep formatters in constants and derive variants withwith...methods.- Use the ISO constants (or plain
toString/parse) for data exchange, localized styles orofLocalizedPatternfor people, andofPatternonly for fixed external layouts. - Localized output comes from CLDR and changes between JDK versions, including invisible characters such as U+202F; never parse it or store it.
- Pattern letters are case-sensitive:
uuuu/yyyynotYYYY,MMnotmm,ddnotDD. Pass a locale toofPatternwhen names appear. - For validation, combine
ResolverStyle.STRICTwithuuuu;SMARTsilently turns February 30 into February 28. DateTimeFormatterBuilderhandles optional sections, defaults, custom texts and unusual fields.- The legacy classes carry the bridge methods:
Date.from/toInstant,GregorianCalendar.from/toZonedDateTime,TimeZone.toZoneId, andvalueOf/toLocal...on thejava.sqltypes.
Practice Questions
1. A report prints 2025-12-30 for an invoice dated 30 December 2024. The formatter is ofPattern("YYYY-MM-dd"). What is wrong?
Y is the week-based year. 30 December 2024 is a Monday in ISO week 1 of 2025, so the week-based year is 2025. The month and day still come from the calendar date, which produces a date a year in the future. Replace YYYY with uuuu (or yyyy).
2. Why does LocalDate.parse("2023-02-28", ofPattern("yyyy-MM-dd").withResolverStyle(STRICT)) fail, and how do you fix it?
In strict mode the resolver needs an era to convert year-of-era (y) into a proleptic year, and the pattern has no G. The parsed fields therefore never resolve to a date. Use uuuu-MM-dd, where u is already the proleptic year, or add an era to the pattern and the input.
3. What does ofPattern("uuuu-MM-dd") do with 2023-02-30, and how do you make it reject the input?
The default SMART resolver clamps day-of-month values from 29 to 31 to the last valid day, so it returns 2023-02-28 without complaint. withResolverStyle(ResolverStyle.STRICT) makes it throw a DateTimeParseException. LENIENT would give 2023-03-02.
4. You need to pass a LocalDate to an old method that takes java.util.Date. What conversion is correct, and what decision does it force?
A Date is an instant, and a LocalDate is not, so you must choose a zone and a time of day: Date.from(localDate.atStartOfDay(zone).toInstant()). The choice of zone changes the result, which is exactly the ambiguity the old API hid. If the method really takes a SQL date, use java.sql.Date.valueOf(localDate) instead.
5. Why should a unit test not assert that ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.US).format(t) equals "9:32 AM"?
Localized text comes from CLDR data, which changes between JDK releases. Since JDK 20 the space before AM is a narrow no-break space (U+202F), so the string no longer equals one written with a normal space, and future releases may change other details. Test localized output loosely, or test the values with ISO formatters and leave the presentation layer to a smaller number of focused checks.
Previous: LocalTime, ZonedDateTime and Daylight Saving Time in Java
Next: Locales in Java: Language Tags, Default Locales and Display Names
Related reading
- LocalTime, ZonedDateTime and Daylight Saving Time in Java
- LocalDate, Period and Temporal Adjusters in Java
- Instant and Duration in Java: Points and Spans on the Time Line
- Connection Pools, DataSources and JPA: JDBC in Real Applications
- JDBC Transactions: Commit, Rollback, Isolation, Save Points and Batch Updates

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.