在java中将本地时区转换为GMT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2055407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conversion of local time zone to GMT in java
提问by Sreekar
Am trying convert date which is in local time zone to GMT, i did some thing like this
我正在尝试将本地时区的日期转换为 GMT,我做了这样的事情
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String gmtStrDate = sdf.format(Calendar.getInstance().getTime());
System.out.println("GMT 1"+gmtStrDate);
Date gmtDate = sdf.parse(gmtStrDate);
System.out.println("GMT 2"+gmtDate);
i am getting GMT 1 o/p in GMT tz but GMT 2 o/p is again changing to local time zone...Can any tel me why?
我在 GMT tz 中得到 GMT 1 o/p 但 GMT 2 o/p 再次更改为本地时区...谁能告诉我为什么?
to get the GMT 2 o/p in GMT i did like this :
要在 GMT 中获得 GMT 2 o/p,我是这样做的:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTime(gmtDate);
日历日历 = Calendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTime(gmtDate);
System.out.println("GMT 3 = "+calendar.getTime());
but still GMT 3o/p am getting in local tz. Please suggest on this.
但仍然是格林威治标准时间 3o/p 进入当地 tz。请就此提出建议。
回答by nanda
After 'parse' you have to again format it before printing, e.g.:
在“解析”之后,您必须在打印前再次对其进行格式化,例如:
System.out.println("GMT 2"+sdf.format(gmtDate));
EDIT:The reason is your gmtStrDate
doesn't store any timezone information
编辑:原因是您gmtStrDate
不存储任何时区信息
回答by Satya
import java.util.*;
import java.text.*;
public class CurrentTimeToGMT{
public static void main(String args[]){
Date date = new Date();
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Current Time: "+date);
System.out.println("GMT Time: " + gmtFormat.format(date));
}
}
Output
输出
Current Time: Wed Mar 10 11:21:18 IST 2010 GMT Time: 3/10/10 5:51 AM
回答by pavel
You can do this using this function say you want to convert local time to GMT time and also this will be GMT+6 or GMT+5 then just use this function. This function will return answer.
您可以使用此功能执行此操作,例如您想将当地时间转换为 GMT 时间,并且这将是 GMT+6 或 GMT+5,然后只需使用此功能。此函数将返回答案。
public String getCurrentDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd hh:mm a zzz");
Date date = new Date();
sdf.setTimeZone(TimeZone.getTimeZone("GMT+6:00"));
return sdf.format(date);
}