Here we will see how to get current UTC time in java in different ways.

How to get Current UTC Time:

In older versions of java like before Java8, we can get current UTC time using SimpleDateFormate object like below.

1. Current UTC Time – SimpleDateFormat:

private static Date getCurrentUtcTime() throws ParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    return localDateFormat.parse( simpleDateFormat.format(new Date()) );
}

Output:

Sat Jun 08 04:54:47 IST 2019

2. Current UTC Time – Java8 Instant:

Java 8 brought an excellent new java.time.*package to supplement the old Java Date/Calendar classes. From Java 8 getting the UTC time as simple as creating Instant object like the following.

An Instant class represents a moment of the timeline in UTC as default timezone.

Instant instant = Instant.now();
System.out.println(instant.toString());

Output:

2019-06-08T04:54:47.543Z

3. Current UTC Time – Java8 OffsetDateTime:

UTC time with OffsetDateTime class.

OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
System.out.println(now);

4. Current UTC Time – Joda Time

Add the Joda dependency in your classpath.

pom.xml
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
 <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.10.2</version>
 </dependency>

Using Joda Time API, you can get current UTC time in a single line below.

private static void getCurrentUtcTimeJoda() throws ParseException {
    DateTime now = new DateTime(); // Gives the default time zone.
    DateTime dateTime = now.toDateTime(DateTimeZone.UTC ); // Converting default zone to UTC
    System.out.println(dateTime);
}

Output:

2019-06-08T04:54:47.731Z

Done!

References:

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment