在Java中获取GMT时间 [英] Get GMT Time in Java

查看:2144
本文介绍了在Java中获取GMT时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我尝试过这样的各种选项:

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

但是日期总是在我当地的时区解释。



我做错了什么,如何将java日期转换为GMT?

解决方案

赔率是好的,你在后台做了正确的事情来获取日期,但是没有什么可以表示你没有采取GMT时间,并根据你的机器当前的区域设置格式。

  final Date currentTime = new Date(); 

final SimpleDateFormat sdf =
new SimpleDateFormat(EEE,MMM d,yyyy hh:mm:ss a z);

//在GMT时间给我
sdf.setTimeZone(TimeZone.getTimeZone(GMT));
System.out.println(GMT time:+ sdf.format(currentTime));

关键是使用自己的DateFormat,而不是系统提供的。这样,您可以将DateFormat的时区设置为您想要的,而不是将其设置为区域设置的时区。


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?

解决方案

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.

这篇关于在Java中获取GMT时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆