×

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal time coordinated or coordinated universal time. Sometimes UTC time zone is denoted by the letter Z where Z stands for “Zulu”. It is used to change time from one time zone to another time zone

  • The GMT and UTC are not similar. Because UTC is not a time zone whereas GMT is the time zone. Mainly in Europe and Africa, and also in some parts of the world the GMT Time zone is not used. For displaying it uses 24 hrs or 12 hrs format.
  • UTC is a time standard used for displaying the time zone. Based on UTC we can calculate the time in different regions. For example, by adding a certain number of hours from UTC we can calculate the time in India i.e,(+5:30).For calculation, like addition or subtraction value is Depended upon how many time zones you are away from Greenwich (England) we can calculate. UTC does not affect due to the switch to daylight saving time and is used to store dates and times in databases.
    • java.util.TimeZone is used. If we use java.util.date package there will be some limitations due to several reasons.
    • No time zone.
    • The date is not represented but an instance in time in milliseconds since Nov1, 1970 (UNIX epoch).
  • Different variations are present in the UTC format. Some formats are UTC has been replaced with Z without a space, in ISO-8601 is xx:xx:xx ZUTC. 12 hrs (AM/PM) xx:xx:xx is another UTC format.

Program

Below is the program to display the number of time zones in a system.

import java.text.ParseException;
import java.util.TimeZone;
public class Timezones{
public static void main(String[] args) throws ParseException {
String[] availableIDs = TimeZone.getAvailableIDs();
for(String id : availableIDs) {
System.out.println("Timezone = " + id);
}
}
}

Output:

Timezone = Africa/Abidjan
Timezone = Africa/Accra
Timezone = Africa/Addis_Ababa
Timezone = Africa/Algiers……Timezone = SST
Timezone = VST

To get the time in UTC there are many ways available such as using below are:

  • SimpleDateFormat
  • Java 8 Instant
  • Java8 OffsetDateTime

SimpleDateFormat

In getting the UTC time this class plays a major role. It is mostly used in java8(older versions).

Program:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.text.ParseException;
SimpleDateFormat
public class UtcExample{
public static void main(String args[]){
try {
System.out.println("IST Time is:"+new Date());
System.out.println("UTC Time is: "+getCurrentUtcTime());
}
catch (ParseException e) {
e.printStackTrace();
}
}
public static Date getCurrentUtcTime() throws ParseException {  // handling ParseException
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
// set UTC time zone by using SimpleDateFormat class
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat ldf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
Date d1 = null;
try {
d1 = ldf.parse( sdf.format(new Date()) );
}
catch (java.text.ParseException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return d1;
}}

Output:

IST Time is:Fri Aug 19 21:44:18 IST 2022
UTC Time is: Fri Aug 19 16:14:18 IST 2022

Java 8 Instant

By creating an instance of the Instant object we can get the UTC time. An excellent new Java.time.* package was brought by the jav8 for using the old java Date/Calendar classes. Timeline moment in UTC as the default time zone is defined by the instant class.

Program:

import java.time.Instant;
import java.util.Date;
public class UtcExample{
public static void main(String[] args)
{
System.out.println("IST Time is:"+new Date());
// print current UTC time
System.out.println("UTC Time is: "+getCurrentUtcTime());
}
public static String getCurrentUtcTime() {
String d1;
Instant instant = Instant.now();
d1 = instant.toString();
return d1;
}
}

Output:

IST Time is:Fri Aug 19 22:07:56 IST 2022
UTC Time is: 2022-08-19T16:37:56.270855500Z

Java 8 OffsetDateTime

ForGetting the current UTC time in java it is one of the important class.unchange0 representation of a date-time with an offset is done by this class mainly for storing the date-time field into the precision of nanoseconds.

Program:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Date;
public class UtcExample {
public static void main(String args[])     {
// print current time
System.out.println("IST Time is:"+new Date());
// print current UTC time
System.out.println("UTC Time is: "+getCurrentUtcTime());
}
public static OffsetDateTime getCurrentUtcTime() {
OffsetDateTime d1;
d1 = OffsetDateTime.now(ZoneOffset.UTC);
// pass UTC date to the main method.
return d1;
}}

Output:

IST Time is:Fri Aug 19 22:28:48 IST 2022
UTC Time is: 2022-08-19T16:58:48.397321Z

But among all the above-mentioned ways we mostly use the SimpleDateFormat class to get the time in UTC.


Related Topics

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and...

3 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.