What is this date format? 2011-08-12T20:17:46.384Z
This date format is ISO 8601, using UTC (indicated by the Z
at the end). Parse it swiftly with java.time.Instant
:
To get it back into a string you can format it like this:
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:
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:
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:
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
orOffsetDateTime
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.
Was this article helpful?