如何将本地日期转换为GMT

时间:2012-05-15 10:47:19

标签: java date

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

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

3 个答案:

答案 0 :(得分:22)

这个怎么样 -

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时间 - 2012年5月15日星期五10:54:14 IST 2012

答案 1 :(得分:17)

DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Current DateTime in GMT : " + gmtFormat.format(new Date()));

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


参见

答案 2 :(得分:1)

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