Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get GMT Time in Java

Tags:

java

date

gmt

In Java, I want to get the current time in GMT.

I tried various options like this:

Date date = new Date(); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); date1 = calendar.getTime(); 

But the date is always is interpreted in my local time zone.

What am I doing wrong and how can I convert a java Date to GMT?

like image 603
narayanan Avatar asked Mar 08 '11 17:03

narayanan


People also ask

Is Java date in UTC?

java. util. Date has no specific time zone, although its value is most commonly thought of in relation to UTC.

Is Java Instant always UTC?

Instant objects are by default in UTC time zone. Printing the value of timestamp gives us 2016-11-29T14:23:25.551Z . 'Z' here denotes the UTC+00:00 time zone.

What is UTC format in Java?

UTC) to convert a given instant to UTC instant. 'Z' in string represents the UTC timezone. It is short form of Zulu and can be written as UTC +0:00 . Parse String to OffsetDateTime. import java.


2 Answers

Odds are good you did the right stuff on the back end in getting the date, but there's nothing to indicate that you didn't take that GMT time and format it according to your machine's current locale.

final Date currentTime = new Date();  final SimpleDateFormat sdf =         new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");  // Give it to me in GMT time. sdf.setTimeZone(TimeZone.getTimeZone("GMT")); System.out.println("GMT time: " + sdf.format(currentTime)); 

The key is to use your own DateFormat, not the system provided one. That way you can set the DateFormat's timezone to what you wish, instead of it being set to the Locale's timezone.

like image 173
Edwin Buck Avatar answered Sep 21 '22 21:09

Edwin Buck


I wonder why no one does this:

Calendar time = Calendar.getInstance(); time.add(Calendar.MILLISECOND, -time.getTimeZone().getOffset(time.getTimeInMillis())); Date date = time.getTime(); 

Update: Since Java 8,9,10 and more, there should be better alternatives supported by Java. Thanks for your comment @humanity

like image 23
Harun Avatar answered Sep 20 '22 21:09

Harun