java - 使用 Calendar 和 SimpleDateFormat 将时间转换为 "HH:mm:ss"会增加 1 小时

标签 java android time formatting timezone

请求

我需要将以秒为单位保存的时间 -> 转换为“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"

在最后一个例子中,我得到了正确的结果,但我不明白为什么。

问题

  1. 为什么最后一个案例有效?(而之前的案例却不起作用?)
  2. 我应该如何使用 Calendar 类才能简单地将时间(以秒为单位)传递给它(无需任何解析)?
  3. 还有其他解决方案(另一个类)吗?除了我自己解析它。

最佳答案

不知道您为什么会遇到这个问题。但你可以简单地写一些类似的东西。 整数小时 = 秒/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/

相关文章:

java - 使用依赖注入(inject)在 Web 环境中实现 CQRS 的命令

android - 单元测试Android,从资源中获取字符串

android - 在模拟器上运行我的 Android 应用程序时遇到错误

java - 在服务器上提交表单之前对密码进行哈希处理

c - 循环长度 - 时间控制 - C

time - 如何将分钟转换为天、小时和分钟?

java - 函数法,求球体的体积

java - 将程序输出附加到 JavaFX TextBox

java - 如何开发支持多个API的android应用

c - 该算法(Big-O)的时间复杂度是多少?