Gaurav Kukade
Gaurav Kukade Hi 👋🏼 I'm Gaurav Kukade, a software developer. I write tutorials for Java programming language and related technologies.

How To Get GMT Time In Java?

In Java Programming, sometimes we need date in GMT format. In this quick tutorial, we will see how we can get GMT time in Java.

We will be using the ZonedDateTime class to get the GMT. We can get any zone time using the ZonedDateTime class. You can see this article to learn more about it.

I have given a java program below, it has the getGMTTime() method. This method receives the Date object (java.util.Date) and returns a GMT string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.coderolls.examples;

import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
/**
 * A Java Program to get time in GMT
 * 
 * @author Gaurav Kukade at coderolls.com
 *
 */
public class GMTTimeExample {

	public static void main(String[] args) {
		
		Date date = new Date();
		String gmtTime = getGMTTime(date);
		System.out.println("Print time in GMT: "+gmtTime);

	}
	
	/**
	 * A method to return GMT time string
	 * @param date
	 * @return
	 */
	public static String getGMTTime(Date date) {
		
		DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss O");
		Instant instant = date.toInstant();
		ZonedDateTime zonedDateTime = instant.atZone(ZoneOffset.UTC);
		return customFormatter.format(zonedDateTime);
		
	}
}

In the above program, we have used the DateTimeFormatter. You can check its various patterns in the documentation.

If you are looking to get the current timestamp in java, you can visit this article How To Get Current Timestamp In Java?.

You can check my YouTube channel here.

Join Newsletter
Get the latest news right in your inbox. We never spam!

comments powered by Disqus