Conversion of local time zone to GMT in java

匿名 (未验证) 提交于 2019-12-03 02:18:01

问题:

Am trying convert date which is in local time zone to GMT, i did some thing like this

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?

to get the GMT 2 o/p in GMT i did like this :

Calendar calendar = 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.

回答1:

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 


回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!