Explain Codes LogoExplain Codes Logo

How to parse a date?

java
date-handling
date-formatting
java-date-api
Nikita BarsukovbyNikita Barsukov·Jan 25, 2025
TLDR

Quickly parse a date in Java with LocalDate.parse utilizing a predefined formatter:

// Now you're becoming a time traveler import java.time.LocalDate; import java.time.format.DateTimeFormatter; // here's your DeLorean's dashboard String dateStr = "2023-04-01"; DateTimeFormatter fmt = DateTimeFormatter.ISO_LOCAL_DATE; LocalDate date = LocalDate.parse(dateStr, fmt);

The ISO_LOCAL_DATE takes care of yyyy-MM-dd formats. For more eccentric formats, use DateTimeFormatter.ofPattern. Just don't forget your flux capacitor.

Robust Date Handling — When Special Cases Activates Your Jetpack

Date-Time Mozaic: Using SimpleDateFormat:

For dates like "Thu Jun 18 20:56:02 EDT 2009", make good use of SimpleDateFormat with the matching pattern:

// Dust off your ancient ruins map import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Date; // The relic no one could decipher String complexDateStr = "Thu Jun 18 20:56:02 EDT 2009"; // The Rosetta stone SimpleDateFormat oldFormatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); try { // History disclosed! Date oldDate = oldFormatter.parse(complexDateStr); } catch (ParseException e) { // oops, better luck next century e.printStackTrace(); }

java.time and DateTimeFormatter: The Time Machine Blueprint

Switch to java.time with DateTimeFormatter for a robust date-time navigation. If your legacy clock is still ticking:

// The wormhole is ready! import java.time.Instant; import java.util.Date; // Initiating time jump... Instant instant = dateTime.toInstant(); Date legacyDate = Date.from(instant);

TimeZone: Time Travel Made Easier

You can set the timezone in SimpleDateFormat for smooth time-travel across different time zones:

// Go everywhere in every time! import java.util.TimeZone; // Your universal key SimpleDateFormat sdfWithTz = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); sdfWithTz.setTimeZone(TimeZone.getTimeZone("UTC"));

Dealing with User-Generated Wormholes

While dealing with user-provided data, validate the provided date format and adjust your parsing mechanism accordingly:

// Users always surprise! import net.sourceforge.jdatepicker.impl.JDatePickerImpl; // Wormhole entrance? JDatePickerImpl datePicker = //... Date selectedDate = (Date) datePicker.getModel().getValue();