如何将System.currentTimeMillis转换为时间格式?(HH:MM:SS)

8
我正在尝试将System.currentTimeMillis转换为当前时间格式(hh:mm:ss)。到目前为止,这是我尝试过的,但它没有正常工作。
    Long currentTime = System.currentTimeMillis();

    int hours;
    int minutes;
    int seconds;

    String getSecToStr = currentTime.toString();
    String getTimeStr = getSecToStr.substring(8,13);

    seconds = Integer.parseInt(getTimeStr);

    minutes = seconds / 60;
    seconds -= minutes * 60;

    hours = minutes / 60;
    minutes -= hours * 60;

    String myResult = Integer.toString(hours) + ":" + Integer.toString(minutes) + ":" + Integer.toString(seconds);

    System.out.println("Current Time Is: " + myResult);

有什么想法吗?非常感谢!


它为什么不工作?它与您的期望有何不同? - Lajos Arpad
System.currentTimeMillis()返回一个13位数字。我相信这些数字包括当前的日期和时间。前8个数字是日期,最后5个数字是时间。当我使用String.substring将数字字符8到13分配为我的秒数时,最终结果如下...27:13:12或5:5:4这不是我想要的。我想得到实际的时间。 - cryptic_coder
不是那样的。在这里看看:https://docs.oracle.com/javase/7/docs/api/java/lang/System.html - D Ie
3个回答

11

有一些对象可以帮助您更轻松地完成此操作,例如 SimpleDateFormatDate

首先将时间准备为毫秒数:

Long currentTime = System.currentTimeMillis();

使用SimpleDateFormat选择您所需的格式:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss");

创建日期对象:

Date date = new Date(currentTime);

将该格式应用于您的日期对象:

String time = simpleDateFormat.format(date);

记录日志:

Log.d(TAG, "onCreate: " + time);

结果:

17:05:73

2
使用 hh:mm:ssHH:mm:ss 而不是 HH:MM:SS。 MM 代表月份,SS 是毫秒的一部分。 hh 代表12小时制,HH 代表24小时制。05 代表五月,一个分钟内不能有73秒。 - Kilarn123
1
这些可怕的日期时间类在多年前被现代的java.time类取代,随着JSR 310的采用。建议在2019年使用它们是糟糕的建议。 - Basil Bourque
此答案忽略了时区这个关键问题。 - Basil Bourque

6

总结

不需要使用 System.currentTimeMillis();。可以使用 java.time 类。

LocalTime.now( 
    ZoneId.of( "America/Montreal" )
)
.truncatedTo( 
    ChronoUnit.SECONDS
)
.toString()

12:34:56

java.time

现代方法使用java.time类。永远不要使用可怕的DateCalendar类。
获取当前时间需要一个时区。对于任何给定的时刻,全球的时刻(和日期)因时区而异。
ZoneId z = ZoneId.of( "Australia/Sydney" ) ;

捕获当前所在地区的人们使用的挂钟时间,即该时区的当天时间。获取一个LocalTime对象。

LocalTime lt = LocalTime.now( z ) ;

如果你想使用UTC而不是特定的时区,请传递ZoneOffset.UTC常量。
显然,你想跟踪到整秒的时间。因此,让我们去掉小数秒。
LocalTime lt = LocalTime.now( z ).truncatedTo( ChronoUnit.SECONDS ) ;

通过调用toString生成标准ISO 8601格式的文本。
String output = lt.toString() ;

关于java.time

java.time框架是Java 8及更高版本内置的。这些类替代了老旧的传统日期时间类,如java.util.DateCalendarSimpleDateFormat

Joda-Time项目现在处于维护模式,建议迁移到java.time类。

欲了解更多信息,请参阅Oracle教程。并在Stack Overflow中搜索许多示例和说明。规范为JSR 310

您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC驱动程序。无需字符串,也不需要java.sql.*类。

如何获得java.time类?

enter image description here


嗨,Basil,你的回答很好,但这种方法需要API级别26,而许多设备仍在使用低于API 26的版本。我建议你强调你的答案适用于API 26或更高版本。 - Ally
@Ali请查看答案底部新增的ThreeTenABP链接。 - Basil Bourque

4
以下内容等同于日期格式HH:mm:ss。
String.format("%1$TH:%1$TM:%1$TS", System.currentTimeMillis())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接