【问题标题】:How Do I Convert System.currentTimeMillis To Time Format? (HH:MM:SS) [duplicate]如何将 System.currentTimeMillis 转换为时间格式? (HH:MM:SS)[重复]
【发布时间】:2019-09-24 04:52:20
【问题描述】:

我正在尝试将 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);

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

【问题讨论】:

标签: java android


【解决方案1】:

您可以使用一些对象来简化此操作,例如 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

【讨论】:

  • 使用hh:mm:ssHH:mm:ss 代替HH:MM:SS。 MM 是月份,SS 是毫秒的一部分。 hh 表示 12 小时格式,HH 表示 24 小时格式。 05 是五月,你不能在一分钟内有 73 秒
  • 这些糟糕的日期时间类在几年前被现代 java.time 类所取代,并采用了 JSR 310。建议在 2019 年使用它们是很糟糕的建议。跨度>
  • 这个答案忽略了时区的关键问题。
【解决方案2】:

tl;博士

不需要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 常量。

显然您想跟踪whole second 的时间。所以让我们lop off 小数秒。

LocalTime lt = LocalTime.now( z ).truncatedTo( ChronoUnit.SECONDS ) ;

通过调用toString 以标准 ISO 8601 格式生成文本。

String output = lt.toString() ;

关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

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

从哪里获得 java.time 类?

【讨论】:

  • 嗨,Basil,一个很好的答案,但这种方法需要 API 级别 26,许多设备仍然使用低于 API 26 的设备。我想您突出显示 API 26 或更高版本的答案。
  • @Ali 查看添加到 ThreeTenABP 答案底部新部分的链接。
【解决方案3】:

以下等价于日期格式HH:mm:ss

String.format("%1$TH:%1$TM:%1$TS", System.currentTimeMillis())

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 2019-07-04
    • 1970-01-01
    • 2019-11-15
    • 2014-01-29
    • 2014-03-27
    相关资源
    最近更新 更多