×

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

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Palindrome number program in Java

Write java program to check if a number is palindrome in Java? A number that does not change on reversing is called a palindrome number. In other words, when reversing the...

3 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.