Explain Codes LogoExplain Codes Logo

Convert timestamp in milliseconds to string formatted time in Java

java
date-formatting
java-time
simpledateformat
Alex KataevbyAlex Kataev·Nov 26, 2024
TLDR

Convert a millisecond timestamp into a formatted date and time string in Java using SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedTime = sdf.format(new Date(System.currentTimeMillis())); System.out.println(formattedTime); // Outputs "2023-01-28 13:45:30"

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 🕒).
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // Consistent across the globe!

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:

Instant instant = Instant.ofEpochMilli(System.currentTimeMillis()); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("UTC")); String formattedTime = formatter.format(instant); System.out.println(formattedTime); // "2023-01-28 13:45:30" - Time travel, anyone?

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.

sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // It's the world standard after all!

If you can stray from the Java Standard Library, Joda-Time or Apache Commons Lang offer simplifications in duration formatting:

String formattedDuration = DurationFormatUtils.formatDurationHMS(timeMillis); System.out.println(formattedDuration); // "1:23:45.678", proof that every millisecond counts!