Explain Codes LogoExplain Codes Logo

How can I get the current date and time in UTC or GMT in Java?

java
date-time
joda-time
timezone
Alex KataevbyAlex Kataev·Aug 5, 2024
TLDR

To get the current UTC time in Java, use the Instant class:

// Time travel toolkit ready! Instant utcNow = Instant.now(); System.out.println(utcNow);

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:

// No time zone confusion here! ZonedDateTime zonedUtcNow = ZonedDateTime.now(ZoneOffset.UTC); System.out.println(zonedUtcNow);

This gives you an explicit timestamp in UTC. Zero OffsetDateTime works well:

// Like a GPS for time! OffsetDateTime offsetUtcNow = OffsetDateTime.now(ZoneOffset.UTC); System.out.println(offsetUtcNow);

Tune in to correct frequency (Precision and formatting)

In Java 9 and higher, Clock gives you nanosecond accuracy:

// Split-second accuracy? Yes, please! Clock clock = Clock.systemUTC(); Instant preciseNow = Instant.now(clock); System.out.println(preciseNow);

To format your timestamp, DateTimeFormatter is your friend:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Like a time artist! String formattedUtc = utcNow.format(formatter); System.out.println(formattedUtc);

Never miss a time stamp (Parsing and accuracy)

For string dates and times, precise parsing and formatting are essential:

DateTimeFormatter parser = DateTimeFormatter.ISO_ZONED_DATE_TIME; // Teleportation portal activated! ZonedDateTime parsedZonedUtc = ZonedDateTime.parse("2023-04-01T18:00:00Z", parser); System.out.println(parsedZonedUtc);

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:

// Let's go on a Joda journey! org.joda.time.Instant jodaInstant = new org.joda.time.Instant(); System.out.println(jodaInstant);

Joda-Time is a time savior for Android projects or systems living in a pre-Java 8 era.