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?
java. util. Date has no specific time zone, although its value is most commonly thought of in relation to 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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With