Format and parse dates
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A DateTimeFormatter turns a date into text in the style you choose, such as 15-03-2024 or Fri, 15 Mar 2024, and reads such text back into a date. It lives in java.time.format.
Formatting with ofPattern
Printing a LocalDate gives ISO text like 2024-03-15. That suits machines, but an Indian marksheet or train ticket shows 15-03-2024 or 15 Mar 2024. A pattern is a short code string where each letter stands for one part of the date.
Example 1 · Common display patterns
import java.time.LocalDate;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.Locale;
public class PatternsDemo { static final DateTimeFormatter INDIAN = DateTimeFormatter.ofPattern("dd-MM-yyyy"); static final DateTimeFormatter SLASHES = DateTimeFormatter.ofPattern("dd/MM/yyyy"); static final DateTimeFormatter SHORT = DateTimeFormatter.ofPattern("d MMM yyyy", Locale.ENGLISH); static final DateTimeFormatter LONG = DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy", Locale.ENGLISH); static final DateTimeFormatter TICKET = DateTimeFormatter.ofPattern("EEE dd MMM, hh:mm a", Locale.ENGLISH); static final DateTimeFormatter LOG = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) { LocalDate exam = LocalDate.of(2024, 3, 5); LocalDateTime train = LocalDateTime.of(2024, 3, 15, 14, 30, 5);
System.out.println(exam.format(INDIAN)); System.out.println(exam.format(SLASHES)); System.out.println(exam.format(SHORT)); System.out.println(exam.format(LONG)); System.out.println(train.format(TICKET)); System.out.println(train.format(LOG)); System.out.println(LONG.format(exam)); }}05-03-2024 05/03/2024 5 Mar 2024 Tuesday, 5 March 2024 Fri 15 Mar, 02:30 PM 2024-03-15 14:30:05 Tuesday, 5 March 2024
What this code does
ddpads the day to two digits (05), whileddoes not (5).MMMandEEEgive short names,MMMMandEEEEgive full names, in the locale passed to the formatter.hh:mm agives02:30 PMandHH:mm:ssgives14:30:05. Each formatter is astatic finalconstant, andformatter.format(date)is the same asdate.format(formatter).
- Date:
d/ddday,M/MM/MMM/MMMMmonth,yyyyyear,EEE/EEEEday name. - Time:
HHhour 0 to 23,hhhour 1 to 12,mmminute,sssecond,aAM or PM. - Text in single quotes is printed as it is:
"dd MMM yyyy 'at' hh:mm a". -,/,,,:and spaces can be used directly as separators.
Create a formatter with DateTimeFormatter.ofPattern("dd-MM-yyyy") and call date.format(formatter). The result is a String; the date itself does not change. Repeating a letter changes the style: M gives 3, MM gives 03, MMM gives Mar and MMMM gives March. A formatter is immutable and thread-safe, which means many threads can use one object at the same time without errors. So create it once, as a static final constant, and reuse it everywhere.
Built-in ISO formatters
For files, databases and APIs, use a standard format instead of a made-up pattern. DateTimeFormatter has ready-made constants: ISO_LOCAL_DATE (2024-03-15), ISO_LOCAL_DATE_TIME (2024-03-15T20:00:00), ISO_OFFSET_DATE_TIME (2024-03-15T20:00:00+05:30), ISO_INSTANT (2024-03-15T14:30:00Z) and BASIC_ISO_DATE (20240315).
Example 2 · Built-in ISO formatters for files and APIs
import java.time.Instant;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;import java.time.format.DateTimeFormatter;
public class IsoFormatsDemo { public static void main(String[] args) { LocalDate d = LocalDate.of(2024, 3, 15); LocalDateTime dt = LocalDateTime.of(2024, 3, 15, 20, 0); ZonedDateTime z = dt.atZone(ZoneId.of("Asia/Kolkata")); Instant i = z.toInstant();
System.out.println(d.format(DateTimeFormatter.ISO_LOCAL_DATE)); System.out.println(d.format(DateTimeFormatter.BASIC_ISO_DATE)); System.out.println(dt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); System.out.println(z.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)); System.out.println(DateTimeFormatter.ISO_INSTANT.format(i)); System.out.println(LocalDate.parse("20240315", DateTimeFormatter.BASIC_ISO_DATE)); }}2024-03-15 20240315 2024-03-15T20:00:00 2024-03-15T20:00:00+05:30 2024-03-15T14:30:00Z 2024-03-15
What this code does
- ISO formatters always print seconds in date-times (
20:00:00), unliketoString().ISO_OFFSET_DATE_TIMEadds+05:30, andISO_INSTANTshows the same moment in UTC. BASIC_ISO_DATE(20240315) is common in file names and bank statements. The same constants also parse, as the last line shows.
The rule of thumb: ISO formats for machines, ofPattern for people. Any program in any language can read ISO text without guessing whether 03/04 means March or April.
Parsing user input safely
To read text, pass the formatter to parse: LocalDate.parse("15-03-2024", formatter). If the text does not match, Java throws DateTimeParseException. User input is often wrong, so catch it and show a helpful message instead of crashing. Call trim() first to remove stray spaces.
Example 3 · Parsing user input and handling errors
import java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.time.format.DateTimeParseException;
public class ParseInputDemo { static final DateTimeFormatter TWO_DIGITS = DateTimeFormatter.ofPattern("dd-MM-yyyy"); static final DateTimeFormatter FLEXIBLE = DateTimeFormatter.ofPattern("d-M-yyyy");
static String read(String input, DateTimeFormatter f) { try { LocalDate d = LocalDate.parse(input.trim(), f); return "OK " + d; } catch (DateTimeParseException e) { return "Please enter a date like 15-03-2024 (you typed \"" + input + "\")"; } }
public static void main(String[] args) { String[] inputs = {"15-03-2024", " 15-03-2024 ", "15-3-2024", "15/03/2024", "2024-03-15"}; for (String in : inputs) { System.out.println("dd-MM-yyyy: " + read(in, TWO_DIGITS)); System.out.println("d-M-yyyy: " + read(in, FLEXIBLE)); } }}dd-MM-yyyy: OK 2024-03-15 d-M-yyyy: OK 2024-03-15 dd-MM-yyyy: OK 2024-03-15 d-M-yyyy: OK 2024-03-15 dd-MM-yyyy: Please enter a date like 15-03-2024 (you typed "15-3-2024") d-M-yyyy: OK 2024-03-15 dd-MM-yyyy: Please enter a date like 15-03-2024 (you typed "15/03/2024") d-M-yyyy: Please enter a date like 15-03-2024 (you typed "15/03/2024") dd-MM-yyyy: Please enter a date like 15-03-2024 (you typed "2024-03-15") d-M-yyyy: Please enter a date like 15-03-2024 (you typed "2024-03-15")
What this code does
parse(text, formatter)throwsDateTimeParseExceptionwhen the text does not match, so the method catches it and returns a friendly message.trim()removes the stray spaces around the second input.dd-MM-yyyyneeds two digits, so15-3-2024fails there but passes withd-M-yyyy. Slashes and ISO order fail with both, because the separators and order must match the pattern.
Example 4 · Trap: 31 February is accepted unless you parse strictly
import java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.time.format.DateTimeParseException;import java.time.format.ResolverStyle;
public class StrictParseDemo { public static void main(String[] args) { DateTimeFormatter smart = DateTimeFormatter.ofPattern("dd-MM-yyyy"); DateTimeFormatter strictYyyy = DateTimeFormatter.ofPattern("dd-MM-yyyy").withResolverStyle(ResolverStyle.STRICT); DateTimeFormatter strict = DateTimeFormatter.ofPattern("dd-MM-uuuu").withResolverStyle(ResolverStyle.STRICT);
System.out.println("smart, 31-02-2024: " + LocalDate.parse("31-02-2024", smart));
try { System.out.println(LocalDate.parse("15-03-2024", strictYyyy)); } catch (DateTimeParseException e) { System.out.println("strict with yyyy, 15-03-2024: failed"); }
System.out.println("strict with uuuu, 15-03-2024: " + LocalDate.parse("15-03-2024", strict)); try { System.out.println(LocalDate.parse("31-02-2024", strict)); } catch (DateTimeParseException e) { System.out.println("strict with uuuu, 31-02-2024: " + e.getMessage()); } }}smart, 31-02-2024: 2024-02-29 strict with yyyy, 15-03-2024: failed strict with uuuu, 15-03-2024: 2024-03-15 strict with uuuu, 31-02-2024: Text '31-02-2024' could not be parsed: Invalid date 'FEBRUARY 31'
What this code does
- The default smart mode quietly turns 31 February into 29 February. A date-of-birth form would save a date the student never typed.
- Strict mode rejects it with "Invalid date 'FEBRUARY 31'". In strict mode the year must be
uuuu: withyyyy(year of era) even a correct date fails to parse.
dd and MM expect exactly two digits, so 15-3-2024 fails with dd-MM-yyyy. If people type one or two digits, use d-M-yyyy, which accepts both. There is a quiet trap. By default ofPattern parses in smart mode: it fixes a day that is too big for its month instead of failing. 31-02-2024 silently becomes 29 February. To reject impossible dates, add .withResolverStyle(ResolverStyle.STRICT) and write the year as uuuu. In strict mode, yyyy means "year of an era" and needs an era, so it fails on every date; uuuu is the plain year.
Order of execution
Parse a typed date safely
Tap the steps in the order the program runs them.
Pattern traps: MM vs mm, yyyy vs YYYY, hh vs HH
Pattern letters are case-sensitive, and the wrong case often compiles and runs with no error.
Example 5 · Pattern traps: mm, YYYY, hh and DD
import java.time.LocalDate;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.time.temporal.UnsupportedTemporalTypeException;import java.util.Locale;
public class PatternTrapsDemo { public static void main(String[] args) { LocalDate date = LocalDate.of(2024, 3, 15); LocalDateTime dt = LocalDateTime.of(2024, 3, 15, 14, 7); LocalDate newYearsEve = LocalDate.of(2024, 12, 31);
try { System.out.println(date.format(DateTimeFormatter.ofPattern("dd-mm-yyyy"))); } catch (UnsupportedTemporalTypeException e) { System.out.println("dd-mm-yyyy on a date: " + e.getMessage()); } System.out.println("dd-mm-yyyy on 14:07: " + dt.format(DateTimeFormatter.ofPattern("dd-mm-yyyy"))); System.out.println("dd-MM-YYYY on 31 Dec: " + newYearsEve.format(DateTimeFormatter.ofPattern("dd-MM-YYYY", Locale.ENGLISH))); System.out.println("dd-MM-yyyy on 31 Dec: " + newYearsEve.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))); System.out.println("hh:mm on 14:07: " + dt.format(DateTimeFormatter.ofPattern("hh:mm"))); System.out.println("hh:mm a on 14:07: " + dt.format(DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH))); System.out.println("DD-MM-yyyy on 15 Mar: " + date.format(DateTimeFormatter.ofPattern("DD-MM-yyyy"))); }}dd-mm-yyyy on a date: Unsupported field: MinuteOfHour dd-mm-yyyy on 14:07: 15-07-2024 dd-MM-YYYY on 31 Dec: 31-12-2025 dd-MM-yyyy on 31 Dec: 31-12-2024 hh:mm on 14:07: 02:07 hh:mm a on 14:07: 02:07 PM DD-MM-yyyy on 15 Mar: 75-03-2024
What this code does
mmis minutes. ALocalDatehas no minutes, so it throws; a date-time silently prints07where the month should be.YYYYturns 31 December 2024 into 2025 because that day belongs to week 1 of 2025.hhwithoutahides the afternoon, andDDprints the day of the year, 75.
MMis month,mmis minute.dd-mm-yyyyon aLocalDatethrowsUnsupportedTemporalTypeException; on a date-time it prints the minute where the month should be.yyyyis the year,YYYYis the week-based year, the year that owns the week the date falls in. They differ only on a few days near New Year, so the bug hides for months: 31 December 2024 prints as 2025.HHis the 24-hour clock,hhthe 12-hour clock.hhwithoutaprints 14:30 as02:30, and nobody can tell morning from afternoon.ddis the day of the month,DDis the day of the year: 15 March prints as75.
Month names with a Locale
A Locale names a language and region, such as English or French. Text parts of a pattern (MMM, MMMM, EEE, EEEE and a) are printed in the formatter's locale. Without one, Java uses the computer's default locale, which differs between laptops and servers.
Example 6 · Month names with a Locale
import java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.time.format.DateTimeParseException;import java.util.Locale;
public class LocaleNamesDemo { public static void main(String[] args) { LocalDate d = LocalDate.of(2024, 3, 15); String pattern = "EEEE, d MMMM yyyy";
System.out.println("English: " + d.format(DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH))); System.out.println("French: " + d.format(DateTimeFormatter.ofPattern(pattern, Locale.FRENCH)));
DateTimeFormatter in = DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH); System.out.println("Parsed: " + LocalDate.parse("15 Mar 2024", in)); try { LocalDate.parse("15 MAR 2024", in); } catch (DateTimeParseException e) { System.out.println("15 MAR 2024: " + e.getMessage()); } }}English: Friday, 15 March 2024 French: vendredi, 15 mars 2024 Parsed: 2024-03-15 15 MAR 2024: Text '15 MAR 2024' could not be parsed at index 3
What this code does
- The same pattern prints different words in each locale. Passing
Locale.ENGLISHkeeps the output the same on every computer, whatever its default language. - Parsing month names uses the locale too, and it matches case:
Marworks,MARfails at index 3, where the month starts.
So pass the locale every time a pattern has words: DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH). The same date prints as vendredi, 15 mars 2024 with Locale.FRENCH. Numbers-only patterns like dd-MM-yyyy do not depend on the locale. Parsing month names is also locale-based and case-sensitive: with Locale.ENGLISH, 15 Mar 2024 parses but 15 MAR 2024 fails.
ZonedDateTime with z adds a short zone name such as IST. That is fine for display, but store and exchange the zone ID Asia/Kolkata.Next step
Check your understanding
12 quick questions