【问题标题】:Conversion of local time zone to GMT in java在java中将本地时区转换为GMT
【发布时间】:2011-01-04 13:16:24
【问题描述】:

我正在尝试将本地时区的日期转换为 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);

我在 GMT tz 获得 GMT 1 o/p 但 GMT 2 o/p 再次更改为本地时区...谁能告诉我为什么?

为了在 GMT 中获得 GMT 2 o/p,我这样做了:

日历 = Calendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTime(gmtDate);

        System.out.println("GMT 3 = "+calendar.getTime());

但格林威治标准时间 3o/p 仍然进入当地 tz。请就此提出建议。

【问题讨论】:

    标签: java timezone


    【解决方案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));
    
      }
    }
    

    输出

    当前时间:2010 年 3 月 10 日星期三 11:21:18 IST 格林威治标准时间:2010 年 3 月 10 日上午 5:51

    【讨论】:

      【解决方案2】:

      “解析”后,您必须在打印前再次对其进行格式化,例如:

      System.out.println("GMT 2"+sdf.format(gmtDate));
      

      编辑: 原因是您的gmtStrDate 没有存储任何时区信息

      【讨论】:

      • 您好,Nanda,感谢您的更新,但在这里,如果我再次对其进行格式化,我将把它作为正确的字符串,但我想输入日期,所以我试图解析它。如果您对此有任何想法,请告诉我。
      • 嗨...如果这是您的意图,那么您得到了正确的结果。不过,您必须正确打印(在 GMT 中)。 System.out.println("GMT 3 = " + sdf.format(calendar.getTime())); calendar.getTime() 包含你想要的数据。
      【解决方案3】:

      您可以使用此函数执行此操作,假设您要将本地时间转换为 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);
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-07
        • 2014-10-25
        • 2021-03-12
        • 1970-01-01
        • 2012-08-28
        • 2023-03-26
        • 2019-03-20
        • 2011-04-23
        相关资源
        最近更新 更多