Change date format in a Java string
Directly transform the String formatted date with SimpleDateFormat. Convert the String to a Date object, then reshape it into the preferred format.
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.
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!
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.
Fitting the mold: Adapting to user's whims
Different users have different tastes in date formats:
- A timestampfor the log-loving system administrators (yyyy-MM-dd HH:mm:ss)
- A friendly human-readable datefor UI-loving customers (EEE, MMM d, 'yy)
Customize patterns to cater to your audience's wants.
Was this article helpful?
