我想针对特定时区(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
现在是 1970 年 1 月 1 日 00:00:00.000 GMT
和 1982 年 1 月 23 日之间的毫秒数, 01:02:03.004 GMT
。
请参阅日期
Javadocs:
/**
* 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
小时与 01
小时):
> 1982-01-23 01:02:03.004+0000
即,因为我使用 calendar.set( Calendar.HOUR, 1 ); 将时间设置为 1(上午 1 点);
,所以我预计时间为 1 点(上午 1 点)而不是 13 点(下午 1 点) .
我哪里出错了?
最佳答案
SimpleDateFormat dateTimeFormat = new SimpleDateFormat( "yyyy-MM-dd' 'hh:mm:ss.SSSZ" );
dateTimeFormat.setTimeZone( gmtTimeZone );
这将为您提供预期的输出。
根据 SimpleDateFormat 的 JavaDoc,日期格式字符串中的“h”将显示为 am/pm (1-12) 中的小时。
编辑: Calendar.HOUR_OF_DAY 应用于设置 24 小时制的小时。
关于Java:SimpleDateFormat 未按所需时区进行格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35304582/