【发布时间】:2016-05-20 04:16:16
【问题描述】:
我想为特定时区 GMT 格式化日期,并且无论应用程序在哪个时区运行,我都希望格式化的结果始终相同。
例如,在 GMT 时区创建 Calendar 实例并填充其字段:
TimeZone gmtTimeZone = TimeZone.getTimeZone( "GMT" );
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone( gmtTimeZone );
calendar.set( Calendar.YEAR, 1982 );
calendar.set( Calendar.MONTH, Calendar.JANUARY );
calendar.set( Calendar.DAY_OF_MONTH, 23 );
calendar.set( Calendar.HOUR, 1 );
calendar.set( Calendar.MINUTE, 2 );
calendar.set( Calendar.SECOND, 3 );
calendar.set( Calendar.MILLISECOND, 4 );
从日历中检索 UTC 时间戳:
Date utcDate = calendar.getTime();
据我了解,utcDate 现在是January 1, 1970, 00:00:00.000 GMT 和January 23, 1982, 01:02:03.004 GMT 之间的毫秒数。
见DateJavadocs:
/**
* Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this <tt>Date</tt> object.
*
* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this date.
*/
创建日期格式化程序并将其时区也设置为 GMT:
SimpleDateFormat dateTimeFormat = new SimpleDateFormat( "yyyy-MM-dd' 'HH:mm:ss.SSSZ" );
dateTimeFormat.setTimeZone( gmtTimeZone );
将日期对象格式化为字符串:
String stringDate = dateTimeFormat.format( utcDate );
现在,当我这样做时:
System.out.println( utcDate.getTime() );
System.out.println( stringDate );
我明白了:
> 380638923004
> 1982-01-23 13:02:03.004+0000
但是,我的预期是(注意 13 hours vs 01 hours):
> 1982-01-23 01:02:03.004+0000
也就是说,因为我使用calendar.set( Calendar.HOUR, 1 ); 将时间设置为 1(凌晨 1 点),所以我预计时间是 1(凌晨 1 点)而不是 13(下午 1 点)。
我哪里错了?
【问题讨论】:
-
所以你想要下午 1 点而不是 1300 小时?
-
因此,根据JavaDocs,“H - 一天中的小时 (0-23)”。也许您应该检查文档以找到更符合您要求的说明符
-
不,我预计凌晨 1 点,因为
calendar.set( Calendar.HOUR, 1 ); -
现在我明白你的意思了,谢谢@MadProgrammer
标签: java date datetime formatting timezone