Convert timestamp in milliseconds to string formatted time in Java
Convert a millisecond timestamp into a formatted date and time string in Java using SimpleDateFormat
:
The magic happens with SimpleDateFormat
, which applies a pattern to a new Date object, given the current time in milliseconds. This results in an instantly understandable formatted string.
Utilizing SimpleDateFormat patterns
When using SimpleDateFormat
, be aware of the pattern characters it expects. Here's a cheat sheet:
yyyy
: Full year.MM
: Month.dd
: Day of the month.HH
: Hours (24hr format).mm
: Minutes.ss
: Seconds.SSS
: Milliseconds (barely visible to humans, but we include it anyway for completeness 🕒).
By setting the time zone to UTC, you evade daylight saving time changes and any location-based oddities.
Shifting to java.time (post Java 8)
From Java 8 onwards, we swap out SimpleDateFormat
with java.time. Here's the updated alternative:
With DateTimeFormatter
, we ensure immutability and thread-safety.
Addressing exceptions and edge cases
Formatting timestamps may sometimes feel like defusing a bomb. Erroneous inputs, out-of-range values, even time zones can become ticking time bombs. To maintain calm and ensure peace:
- Always validate the input timestamp. Don't let "dirty" data interfere.
- Watch out for limit breakers. Keep an eye on the API's maximum capacity.
- Don't let time zones give you the blues. Present times responsibly to global audiences.
Always prepare a try-catch contingency, because exceptions are ninjas - they can appear out of nowhere.
Optimizing performance and exploring alternatives
For the performance-obsessed, be mindful of creating new Date
or SimpleDateFormat
objects. Reuse these instances wherever possible to give the garbage collector less clean up duty.
If you can stray from the Java Standard Library, Joda-Time or Apache Commons Lang offer simplifications in duration formatting:
Was this article helpful?