如何将本地日期转换为GMT [英] How to convert a local date to GMT

查看:102
本文介绍了如何将本地日期转换为GMT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
java.util.Date fromDate = cal.getTime();
System.out.println(fromDate);

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

The above code doesn't print the date in GMT, but rather prints in the local timezone. How do I get a GMT equivalent date from the current date (assuming that the program can run in Japan or SFO)

推荐答案

关于这个 -

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时间 - 星期二5月15日16:24:14 IST 2012款
GMT时间 - 星期二5月15日10:54:14 IST 2012

Test Result :
UTC Time - Tue May 15 16:24:14 IST 2012
GMT Time - Tue May 15 10:54:14 IST 2012

这篇关于如何将本地日期转换为GMT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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