How can I get the current date and time in UTC or GMT in Java?
To get the current UTC time in Java, use the Instant
class:
Instant
accesses UTC time, and gives you an ISO-8601 formatted timestamp.
Picking the best toolkit
To journey through time in Java, you'll need the right tools. The java.time.*
package and Joda-Time have what you need, including immutable objects and a clean API. Don't bother with old, clunky tools like java.util.Date
, Calendar
, and SimpleDateFormat
. These can go rusty and cause problems!
Remember to set your timezone!
Use ZonedDateTime
or OffsetDateTime
with an exact time zone or offset, so you don't end up in the wrong time:
This gives you an explicit timestamp in UTC. Zero OffsetDateTime works well:
Tune in to correct frequency (Precision and formatting)
In Java 9 and higher, Clock
gives you nanosecond accuracy:
To format your timestamp, DateTimeFormatter
is your friend:
Never miss a time stamp (Parsing and accuracy)
For string dates and times, precise parsing and formatting are essential:
Quick tip: Catch DateTimeParseException
to keep your time travel error-free.
Advantages of Joda-Time
Both java.time.*
and Joda-Time give clear, timely results. But sometimes, Joda-Time shines:
Joda-Time is a time savior for Android projects or systems living in a pre-Java 8 era.
Was this article helpful?