请求
我需要将以秒为单位保存的时间 -> 转换为“HH:mm:ss”(以及将来的其他格式)。
例如9
秒 -> “00:00:09”
。
但是,Calendar
类始终增加 +1 小时。我认为这是因为我的时区(即“欧洲/布拉格”)或夏令时。
测试
Date
类的首次简单使用。然后使用不同时区的 Calendar
进行三次,尝试方法 setTimeInMillis()
和 set()
。
// Declarations
Calendar cal;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat( format );
String result;
日期类用法:
// Simple Date class usage
Date date = new Date( timeInSecs * 1000 );
result = simpleDateFormat.format( date ); // WRONG result: "01:00:09"
带有“GMT”的日历类:
// Calendar - Timezone GMT
cal = new GregorianCalendar( TimeZone.getTimeZone( "GMT" ) );
cal.setTimeInMillis( timeInSecs * 1000 );
result = simpleDateFormat.format( cal.getTime() ); // WRONG result: "01:00:09"
cal.set( 1970, Calendar.JANUARY, 1, 0, 0, timeInSecs );
result = simpleDateFormat.format( cal.getTime() ); // WRONG result: "01:00:09"
带有“UTC”的日历类:
// Calendar - Timezone UTC
cal = new GregorianCalendar( TimeZone.getTimeZone( "UTC" ) );
cal.setTimeInMillis( timeInSecs * 1000 );
result = simpleDateFormat.format( cal.getTime() ); // WRONG result: "01:00:09"
cal.set( 1970, Calendar.JANUARY, 1, 0, 0, timeInSecs );
result = simpleDateFormat.format( cal.getTime() ); // WRONG result: "01:00:09"
带有“默认”的日历类 - “欧洲/布拉格”:
// Calendar - Timezone "default" (it sets "Europe/Prague")
cal = new GregorianCalendar( TimeZone.getDefault() );
cal.setTimeInMillis( timeInSecs * 1000 );
result = simpleDateFormat.format( cal.getTime() ); // WRONG result: "01:00:09"
cal.set( 1970, Calendar.JANUARY, 1, 0, 0, timeInSecs );
result = simpleDateFormat.format( cal.getTime() ); // CORRECT result: "00:00:09"
在最后一个例子中,我得到了正确的结果,但我不明白为什么。
问题
- 为什么最后一个案例有效?(而之前的案例却不起作用?)
- 我应该如何使用 Calendar 类才能简单地将时间(以秒为单位)传递给它(无需任何解析)?
- 还有其他解决方案(另一个类)吗?除了我自己解析它。
最佳答案
不知道您为什么会遇到这个问题。但你可以简单地写一些类似的东西。
整数小时 = 秒/3600,
余数 = 秒 % 3600,
分钟 = 余数/60,
秒 = 余数 % 60;
string displayHours= (hours < 10 ? "0" : "") + hours,
displayMinutes= (minutes < 10 ? "0" : "") + minutes ,
displaySec = (seconds < 10 ? "0" : "") + seconds ;
System.out.println(disHour +":"+ displayMinutes+":"+displaySec );
关于java - 使用 Calendar 和 SimpleDateFormat 将时间转换为 "HH:mm:ss"会增加 1 小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26591706/