【问题标题】:Elapsed time format HH:mm:ss经过时间格式 HH:mm:ss
【发布时间】:2015-11-07 11:11:46
【问题描述】:

这是一个简单的问题,但我没有让它工作。

我每秒递增一个变量,并以毫秒为单位将其设置在 GregorianCalendar 中。

我正在使用这种格式HH:mmss 来显示经过的时间。

问题是小时开始显示 01 而不是 00。例如,1 分 35 秒后显示的是:01:01:35 而不是 00:01:35

问题可能出在哪里?

有重要的代码:

GregorianCalendar timeIntervalDone = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); //initially I didn't have the TimeZone set, but no difference
SimpleDateFormat dateTimeIntervalFormat = new SimpleDateFormat("HH:mm:ss");

public String getTimeIntervalDoneAsString() {
    timeIntervalDone.setTimeInMillis(mTimeIntervalDone); //mTimeIntervalDone is the counter: 3seccond -> mTimeIntervalDone = 3000
    return dateTimeIntervalFormat.format(timeIntervalDone.getTime());
}

【问题讨论】:

    标签: java date formatting gregorian-calendar


    【解决方案1】:

    我认为原因是您将时区设置为 GMT-1,但输出是 UTC。请在没有该时区的情况下尝试它,它应该可以工作。

    【讨论】:

    • 没有时区结果是一样的。
    • 哦,抱歉,我没有滚动到最后看到该评论。
    【解决方案2】:

    我终于明白了:

    GregorianCalendar timeIntervalDone = new GregorianCalendar(); 
    SimpleDateFormat dateTimeIntervalFormat = new SimpleDateFormat("HH:mm:ss");
    dateTimeIntervalFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    

    【讨论】:

    • 缺点:它只适用于小于一天(24小时)的时间间隔。
    【解决方案3】:

    您的方法是一种技巧,试图使用日期时间时刻类 (GregorianCalendar) 来表示时间跨度。此外,您的格式不明确,看起来像是一天中的时间而不是持续时间。

    ISO 8601

    另一种方法是使用ISO 8601 描述持续时间的标准方式:PnYnMnDTnHnMnS 其中P 标记开始,T 将年-月-日部分与时-分-秒部分分开.

    java.time

    Java 8 及更高版本中的 java.time 框架取代了旧的 java.util.Date/.Calendar 类。旧的课程已被证明是麻烦的、令人困惑的和有缺陷的。避开他们。

    java.time 框架的灵感来自高度成功的 Joda-Time 库,由 JSR 310 定义,由 ThreeTen-Extra 项目扩展,并在 Tutorial 中进行了解释。

    java.time 框架确实使用 ISO 8601 作为其默认值,这组出色的类缺少一个类来表示整个年-月-日-小时-分钟-秒的时间段。相反,它将概念一分为二。 Period 类处理年-月-日,Duration 类处理小时-分钟-秒。

    Instant now = Instant.now ();
    Instant later = now.plusSeconds ( 60 + 35 ); // One minute and 35 seconds later.
    
    Duration duration = Duration.between ( now , later );
    String output = duration.toString ();
    

    转储到控制台。

    System.out.println ( "output: " + output );
    

    输出:PT1M35S

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-28
      • 2012-12-01
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 2013-05-18
      相关资源
      最近更新 更多