DateFormat 中的零填充小时

发布于 2024-12-25 09:32:26 字数 265 浏览 1 评论 0原文

我试图将时间差显示为字符串,格式为 00:00:00(小时:分钟:秒),以零填充。我有以下代码:

long timeDiff = System.currentTimeMillis() - mStartRecordingTime;
time = DateFormat.format("hh:mm:ss", timeDiff).toString(); 

我在测试它时,timeDiff 不超过几秒,但小时不显示为 00。顺便说一下,我在 JST 时区。

I am trying to display a time difference into a string which follows the form 00:00:00 (hours:minutes:seconds), zero-padded. I have the following code:

long timeDiff = System.currentTimeMillis() - mStartRecordingTime;
time = DateFormat.format("hh:mm:ss", timeDiff).toString(); 

I was testing it when the timeDiff was no more than a few seconds but the hour does not show as 00. I am in the JST timezone by the way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

倾其所爱 2025-01-01 09:32:26

你从哪里得到mStartRecordingTime?在我看来,它不像是在同一语言环境中使用 System.currentTimeMillis() 设置的;如果是的话,那么时间差就会反映实际的差异,这样就会起作用。录制时间似乎以 UTC 时间设定,与 JST 相差 9 个小时。

另一位海报是正确的,用这个值生成的日期将接近纪元,但如果你只是想获取小时、分钟和秒,那么你应该没问题。请记住,您正在处理经过的时间,而不是时钟/日历时间,因此我不希望日期格式(而不是时间格式)适合您。

Where did you get mStartRecordingTime? It doesn't look to me like it was set with System.currentTimeMillis() in the same locale; if it had been, then the time difference would have reflected the actual difference and this would have worked. It appears that the recording time somehow got set with UTC, 9 hours away from JST.

The other poster is correct, a date produced with this value would be near epoch, but if you're just trying to get hours, minutes, and seconds, then you should be all right. Keep in mind that you're dealing with elapsed time, not clock/calendar time, so I wouldn't expect the date formatting (as opposed to time formatting) things to work for you.

如日中天 2025-01-01 09:32:26

使用 SimpleDateFormat

long timeDiff = System.currentTimeMillis() - mStartRecordingTime;
String time = new SimpleDateFormat("hh:mm:ss").format(new Date(timeDiff)); 

Use SimpleDateFormat:

long timeDiff = System.currentTimeMillis() - mStartRecordingTime;
String time = new SimpleDateFormat("hh:mm:ss").format(new Date(timeDiff)); 
草莓酥 2025-01-01 09:32:26

您需要补偿时区。根据您所拥有的,更改日期格式化程序以使用 UTC 作为时区可能是最简单的。以下是一些应该有所帮助的代码:

    long timeDiff = System.currentTimeMillis() - mStartRecordingTime;
    DateFormat df = new SimpleDateFormat("HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    String time = df.format(new Date(timeDiff));

请注意,对“HH”的更改是日期格式,以 24 小时格式显示时间。

You need to compensate for the time zone. With what you have, it is probably easiest to change the date formatter to use UTC as the time zone. Here is some code that should help:

    long timeDiff = System.currentTimeMillis() - mStartRecordingTime;
    DateFormat df = new SimpleDateFormat("HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    String time = df.format(new Date(timeDiff));

Note the change to 'HH' is the date format to display times in a 24 hour format.

英雄似剑 2025-01-01 09:32:26

太长了;博士

Duration.between( 
    LocalTime.of( 12 , 5 , 0 ) ,
    LocalTime.of( 12 , 7 , 0 ) 
).toString()

PT2M

如果您不顾我使用 Duration 的强烈建议,坚持使用不明确/令人困惑的时间格式:

LocalTime.MIN.plus(
    Duration.between( 
        LocalTime.of( 12 , 5 , 0 ) ,
        LocalTime.of( 12 , 7 , 0 ) 
    )
).toString();

00:02

要强制使用所有三个组成部分(小时、分钟、秒),请使用预定义的 DateTimeFormatter.ISO_LOCAL_TIME

LocalTime.MIN.plus(
    Duration.between( 
        LocalTime.of( 12 , 5 , 0 ) ,
        LocalTime.of( 12 , 7 , 0 ) 
    )
).format( DateTimeFormatter.ISO_LOCAL_TIME )

00:02:00

请参阅IdeOne.com 中的实时代码

Moment != span-of-time

不要滥用日期时间类(例如 java.util.Date)来存储经过的时间。这样的课程代表的是一个时刻,而不是一段时间。

避免遗留日期时间类

不要使用麻烦的旧日期时间类,例如 java.util.Date。这些现在已被 java.time 类取代。

即时

Instant 类表示 UTC 中时间轴上的时刻分辨率为纳秒

获取当前时刻。

Instant now = Instant.now();

稍后再模拟。

Instant future = now.plus( Duration.ofMinutes( 5 ) );

Duration

使用 DurationPeriod 对象。其中每一个都代表一个时间跨度,第一个处理天-小时-分钟-秒,第二个处理年-月-日。

Duration duration = Duration.between( now , future );

字符串格式

要将持续时间值呈现为字符串,请勿使用时间格式,因为这样不明确。请改为使用标准ISO 8601 格式的持续时间。此格式 PnYnMnDTnHnMnSP 标记开头。中间的 T 将年-月-日部分与时-分-秒部分分开。例如,两个半小时是PT2H30M。我们这里的五分钟示例是 PT5M

String output = duration.toString();  // PT5M

LocalTime

如果您确实有实际的时间并且希望使用填充零进行格式化,请使用默认格式 LocalTime::toString

LocalTime.now( ZoneId.of( "America/Montreal" ) ).toString();  // 02:03:04.789Z

另一个例子。再次强调,我建议以这种方式滥用LocalTime。 (相反,请坚持使用 Duration 来表示经过的时间。)

LocalTime start = LocalTime.now( ZoneId.of( "America/Montreal" ) );
LocalTime stop = start.plusMinutes( 7 );
Duration d = Duration.between( start , stop );
LocalTime result = LocalTime.MIN.plus( d );  // I do *not* recommend abusing `LocalTime` this way. Use `Duration` instead for elapsed time.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_TIME ;
String output = result.format( f );
System.out.println( "output: " + output );

输出:00:07:00

请参阅IdeOne.com 中的实时代码


关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历, & ; SimpleDateFormat

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

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

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 间隔YearWeekYearQuarter更多

tl;dr

Duration.between( 
    LocalTime.of( 12 , 5 , 0 ) ,
    LocalTime.of( 12 , 7 , 0 ) 
).toString()

PT2M

If, against my strong recommendation to use Duration, you insist on using ambiguous/confusing time-of-day formatting:

LocalTime.MIN.plus(
    Duration.between( 
        LocalTime.of( 12 , 5 , 0 ) ,
        LocalTime.of( 12 , 7 , 0 ) 
    )
).toString();

00:02

To force all three components (hours, minutes, seconds), use the predefined DateTimeFormatter.ISO_LOCAL_TIME.

LocalTime.MIN.plus(
    Duration.between( 
        LocalTime.of( 12 , 5 , 0 ) ,
        LocalTime.of( 12 , 7 , 0 ) 
    )
).format( DateTimeFormatter.ISO_LOCAL_TIME )

00:02:00

See live code in IdeOne.com.

Moment != span-of-time

Do not abuse a date-time class such as java.util.Date to store elapsed time. Such a class represents a moment, not a span of time.

Avoid legacy date-time classes

Do not use troublesome old date-time classes such as java.util.Date. Those are now supplanted by java.time classes.

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Get the current moment.

Instant now = Instant.now();

Simulate a later time.

Instant future = now.plus( Duration.ofMinutes( 5 ) );

Duration

Capture elapsed time with a Duration or Period object. Each of these represent a span of time, the first handles days-hours-minutes-seconds and the second handles years-months-days.

Duration duration = Duration.between( now , future );

String format

To present that duration value as a String, do not use time-of-day formatting as that is ambiguous. Instead use standard ISO 8601 format for durations. This format, PnYnMnDTnHnMnS, marks the beginning with a P. The T in the middle separates the years-months-days portion from the hours-minutes-seconds portion. For example, two and a half hours is PT2H30M. Our example here of five minutes is PT5M.

String output = duration.toString();  // PT5M

LocalTime

If you do have an actual time-of-day and want to format with padding zeros, use the default format of LocalTime::toString.

LocalTime.now( ZoneId.of( "America/Montreal" ) ).toString();  // 02:03:04.789Z

Another example. Again, I do not recommend abusing LocalTime this way. (Instead, stick with Duration for elapsed time.)

LocalTime start = LocalTime.now( ZoneId.of( "America/Montreal" ) );
LocalTime stop = start.plusMinutes( 7 );
Duration d = Duration.between( start , stop );
LocalTime result = LocalTime.MIN.plus( d );  // I do *not* recommend abusing `LocalTime` this way. Use `Duration` instead for elapsed time.
DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_TIME ;
String output = result.format( f );
System.out.println( "output: " + output );

output: 00:07:00

See live code in IdeOne.com.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文