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 - SimpleDateFormatSimpleDateFormat 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. UTCTimeExample1.java Output: 2. Current UTC Time - Java 8 InstantIn 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: UTCTimeExample2.java Output: 3. Current UTC Time - Java8 OffsetDateTimeJava 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: UTCTimeExample3.java Output: 4. Current UTC Time - Joda TimeJava 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: UTCTimeExample4.java Output: 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. UTCTimeExample5.java Output: Next TopicJacobsthal Number in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India