This question already has answers here:
How can I get the current date and time in UTC or GMT in Java?
(31个答案)
7年前关闭。
上面的代码不会在格林尼治标准时间打印日期,而是在当地时区打印。我如何从当前日期获得等效于格林尼治标准时间的日期(假设程序可以在日本或SFO上运行)
测试结果:
UTC时间-2012年5月15日星期二16:24:14
GMT时间-2012年5月15日星期二10:54:14
(31个答案)
7年前关闭。
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
java.util.Date fromDate = cal.getTime();
System.out.println(fromDate);
上面的代码不会在格林尼治标准时间打印日期,而是在当地时区打印。我如何从当前日期获得等效于格林尼治标准时间的日期(假设程序可以在日本或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时间-2012年5月15日星期二16:24:14
GMT时间-2012年5月15日星期二10:54:14