【问题标题】:How to convert a local date to GMT [duplicate]如何将本地日期转换为 GMT [重复]
【发布时间】:2012-05-22 20:51:04
【问题描述】:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
java.util.Date fromDate = cal.getTime();
System.out.println(fromDate);

上面的代码不会以 GMT 打印日期,而是以当地时区打印。如何从当前日期获取 GMT 等效日期(假设程序可以在日本或 SFO 运行)

【问题讨论】:

    标签: java date


    【解决方案1】:
    DateFormat gmtFormat = new SimpleDateFormat();
    TimeZone gmtTime = TimeZone.getTimeZone("GMT");
    gmtFormat.setTimeZone(gmtTime);
    System.out.println("Current DateTime in GMT : " + gmtFormat.format(new Date()));
    

    更一般地,您可以通过这种方式转换到任何(有效)时区


    【讨论】:

    • gmtFormat.format(new Date()) 返回类型是字符串。但我想约会。
    • 你可以parse()那个String来创建Date实例
    • 解析后,它会立即恢复为本地时区格式。就我而言,它将其转换回 IST。如何在 GMT 中保存
    【解决方案2】:

    这个怎么样-

    public static void main(String[] args) throws IOException {
        Test test=new Test();
        Date fromDate = Calendar.getInstance().getTime();
        System.out.println("UTC Time - "+fromDate);
        System.out.println("GMT Time - "+test.cvtToGmt(fromDate));
    }
    private  Date cvtToGmt( Date date ){
        TimeZone tz = TimeZone.getDefault();
        Date ret = new Date( date.getTime() - tz.getRawOffset() );
    
        // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
        if ( tz.inDaylightTime( ret )){
            Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );
    
            // check to make sure we have not crossed back into standard time
            // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
            if ( tz.inDaylightTime( dstDate )){
                ret = dstDate;
            }
         }
         return ret;
    }
    

    测试结果 :
    UTC 时间 - 2012 年 5 月 15 日星期二 16:24:14 IST
    GMT 时间 - 2012 年 5 月 15 日星期二 10:54:14 IST

    【讨论】:

    • 非常感谢。它帮助我
    • 你欢迎@HaiderAli :)
    【解决方案3】:

    喜欢这个SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 1970-01-01
      • 2017-03-24
      • 2012-02-15
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 2011-08-29
      相关资源
      最近更新 更多