Explain Codes LogoExplain Codes Logo

Change date format in a Java string

java
date-formatting
localdatetime
datetimeformatter
Anton ShumikhinbyAnton Shumikhin·Nov 2, 2024
TLDR

Directly transform the String formatted date with SimpleDateFormat. Convert the String to a Date object, then reshape it into the preferred format.

import java.text.SimpleDateFormat; import java.text.ParseException; String oldFormat = "dd/MM/yyyy"; String newFormat = "yyyy-MM-dd"; String oldDateString = "22/01/2023"; try { SimpleDateFormat oldFormatter = new SimpleDateFormat(oldFormat); Date date = oldFormatter.parse(oldDateString); SimpleDateFormat newFormatter = new SimpleDateFormat(newFormat); String newDateString = newFormatter.format(date); System.out.println(newDateString); // Prints: 2023-01-22 } catch (ParseException e) { e.printStackTrace(); // Oops, here be dragons! Handle your exception. }

The date String must match the oldFormat, and handle ParseException where required.

Understand the power of java.time

Modern solutions with LocalDateTime and DateTimeFormatter

Java 8's java.time package offers you the LocalDateTime and DateTimeFormatter classes for parsing and formatting dates. These classes are thread-safe, so no more worrying about Jekyll and Hyde moments with SimpleDateFormat.

import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; String dateTimeString = "22/01/2023 14:30"; DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"); DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, inputFormatter); String formattedDateTime = dateTime.format(outputFormatter); System.out.println(formattedDateTime); // Prints: 2023-01-22 14:30

Time travel with ZonedDateTime

If you need to juggle time zones, ZonedDateTime is your superhero. It manages all the timezone semantics so you don't have to. No more temporal migraines!

import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.ZoneId; String zonedDateTimeString = "22/01/2023 14:30 +02:00"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm Z"); ZonedDateTime zonedDateTime = ZonedDateTime.parse(zonedDateTimeString, formatter); formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX").withZone(ZoneId.systemDefault().normalized()); String formattedZonedDateTime = zonedDateTime.format(formatter); System.out.println(formattedZonedDateTime); // Prints: 2023-01-22 14:30:00+02:00

Accentuating the pattern sensitivity: A guide

It's wise to learn the language of date patterns:

  • yyyy: year
  • MM: month
  • dd: day
  • HH: hour (24-hour)
  • mm: minute
  • ss: second
  • sss: millisecond

Avoid these faux pas:

  • Using five 'y's (e.g., "yyyyy") — Four shall you number them!
  • Confusing "MM" (month) with "mm" (minutes) — Happens more often than you'd think!
  • Using "YYYY" for year — "yyyy" keeps it simple!

Practical applications and coding wizardry

Handling exceptions: Catch 'em all!

While parsing dates, exceptions can sneak up on you. For SimpleDateFormat, we catch a ParseException. For java.time classes, it's DateTimeParseException.

try { // Parse your date here } catch (Exception e) { // A wild exception appeared! Handle it here }

Fitting the mold: Adapting to user's whims

Different users have different tastes in date formats:

  • A timestamp for the log-loving system administrators (yyyy-MM-dd HH:mm:ss)
  • A friendly human-readable date for UI-loving customers (EEE, MMM d, 'yy)

Customize patterns to cater to your audience's wants.

// Programmer: I do love a good timestamp! String patternForLogs = "yyyy-MM-dd HH:mm:ss"; // User: I just want to know what day it is! String patternForUI = "EEE, MMM d, 'yy";