Explain Codes LogoExplain Codes Logo

What is this date format? 2011-08-12T20:17:46.384Z

java
date-format
java-8
best-practices
Nikita BarsukovbyNikita Barsukov·Jan 13, 2025
TLDR

This date format is ISO 8601, using UTC (indicated by the Z at the end). Parse it swiftly with java.time.Instant:

Instant instant = Instant.parse("2011-08-12T20:17:46.384Z");

To get it back into a string you can format it like this:

String backToISO = DateTimeFormatter.ISO_INSTANT.format(instant);

Some projects may still be running older Java versions. In that case, consider using ThreeTen-Backport library to backport java.time functionality.

Travelling through time with SimpleDateFormat

Prior to the release of Java 8, date-time operations were slightly more complicated. We had to use SimpleDateFormat to handle ISO 8601 timestamps:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); // Just your average everyday date pattern. Nothing to see here. sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // Let's all align with Greenwich, shall we? Date date = sdf.parse("2011-08-12T20:17:46.384Z"); // Voilà! Your time machine is ready.

When using this method, it's important to explicitly set the Locale to avoid any unexpected changes.

Dealing with time zones: Java's night shift

Parsing dates should incorporate time zones. When dealing with ZonedDateTime, here's what you can do:

DateTimeFormatter zoneFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); // Because time zones, eh? Can't live with them, can't live without them. ZonedDateTime zonedDateTime = ZonedDateTime.parse("2011-08-12T20:17:46.384Z", zoneFormatter); // Zoned and primed.

This ZonedDateTime example handles scenarios where the string contains zone information other than 'Z' (i.e. not just in UTC).

Java's great leap forward: java.time

Java 8 introduced java.time, a momentous change that simplifies parsing ISO 8601 timestamps:

OffsetDateTime dateWithOffset = OffsetDateTime.parse("2011-08-12T20:17:46.384Z"); // Ultra-elegant date parsing, brought to you by java.time.

If your string contains the UTC specifier ('Z'), you can parse it directly using Instant.parse, without any formatting or transformation. How fantastically convenient!

Date and Time Warp: Best practices

Here are some golden rules to follow while dealing with date and time:

  • Use java.time for all your modern applications: The Java 8 way of date and time.
  • When showing time to users, combine ZonedDateTime or OffsetDateTime with user's time zone.
  • Working on Android or older Java versions? Make use of backport libraries like ThreeTenABP or ThreeTen-Backport.
  • If dealing with international systems, working in UTC and converting to local times when presenting to the user is the way to go.