首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将本地日期转换为GMT

如何将本地日期转换为GMT
EN

Stack Overflow用户
提问于 2012-05-15 18:47:19
回答 3查看 58K关注 0票数 15
代码语言:javascript
运行
复制
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
java.util.Date fromDate = cal.getTime();
System.out.println(fromDate);

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-05-15 18:54:25

不如这样吧-

代码语言:javascript
运行
复制
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

票数 22
EN

Stack Overflow用户

发布于 2012-05-15 18:50:16

代码语言:javascript
运行
复制
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Current DateTime in GMT : " + gmtFormat.format(new Date()));

通常情况下,您可以通过这种方式转换为任何(有效)时区

请参阅

  • DateFormat
票数 18
EN

Stack Overflow用户

发布于 2012-05-15 18:55:33

像这样的SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10599109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档