How to get UTC time in Java?
In Java, we often need to convert a time of one timezone into another timezone. UTC stands for Universal Time Coordinated (UTC). Before commence of UTC it was called Greenwich Mean Time (GMT). Indian users need to convert the IST time into UTC time when working in different time zones.
In Java, there are many ways to get UTC time which are given below:
1. Current UTC Time - SimpleDateFormat
SimpleDateFormat is one of the most important classes which plays an important role in getting UTC time. SimpleDateFormat is mainly used in the older version of Java, such as Java8.
Let's take an example to understand how we can get UTC time by SimpleDateFormat in Java8.
2. Current UTC Time - Java 8 Instant
In Java8, we can easily get the current UTC time by creating an instance of the Instant object. Java8 brought an excellent new Java.time.* package for using the old java Date/Calendar classes. The Instant class defines a moment of the timeline in UTC as the default time zone.
Let's take an example to understand how we can get current UTC time by using Java8 Instant:
3. Current UTC Time - Java8 OffsetDateTime
Java OffsetDateTime class is one of the important class to get current UTC time. OffsetDateTime is an immutable representation of a date-time with an offset that is mainly used for storing date-time fields into the precision of nanoseconds.
Let's take an example to understand how we can get current UTC time by using OffsetDateTime class:
4. Current UTC Time - Joda Time
Java Joda Time API is an important API that can also be used to get the current UTC time. In order to use Joda Time, we need to add the following dependency in our POM.xml file:
Let's take an example to understand how we can get current UTC time by usingJoda Time API:
All the above-discussed methods are used to get the current UTC time in Java, and we mostly use SimpleDateFormat class for getting UTC time.
Let's take one more example to understand how we can convert the given time into UTC time.