转换时间戳字符串“ HH:mm:ss”到持续时间 [英] Converting Timestamp string "HH:mm:ss" to Duration

查看:138
本文介绍了转换时间戳字符串“ HH:mm:ss”到持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题中所说的那样,我已经能够从文本文件中分离出一个字符串,该字符串包含格式为 HH:mm:ss的持续时间。我将如何将其转换为持续时间?我需要将其转换为以1小时表示此时间戳的double值,因此,如果它是 08:30:00,则需要double值必须为8.5。不确定确切如何进行转换,似乎时间在Java中是一个棘手的话题。任何帮助将不胜感激,即使只是您说使用该类,这样我也可以查找并找出答案。

Just like the title says, I've been able to isolate from a text file a string containing a duration in the format of "HH:mm:ss." How would I go about converting it to a duration? I need to convert it to a double that expresses this timestamp in terms of 1 hour, so if it's "08:30:00" I need the double to have a value of 8.5. Not sure exactly how to go about converting it, seems that time is a tricky subject in Java. Any help would be greatly appreciated, even if it's just you saying "use this class" so I can look it up and figure it out.

谢谢!

推荐答案

tl; dr



tl;dr

Duration.between ( 
    LocalTime.MIN , 
    LocalTime.parse ( "08:30:00" ) 
).toString()




PT8H30M

PT8H30M



持续时间与时间戳



如果通过字符串 08:30:00 表示时间跨度为八个半小时,则执行不要使用术语时间戳。 持续时间一词是正确的并且经常使用。并避免使用HH:MM:SS格式,因为它太含糊了,似乎是一天中的某个时间。而是使用下面讨论的标准格式。

Duration vs Timestamp

If by the string 08:30:00 you mean "eight and a half hours" span of time, then do not use the term "timestamp". The word "duration" is correct and commonly used. And avoid that format of HH:MM:SS because it is so ambiguous, appearing to be a time-of-day. Instead use the standard format discussed below.

如果字符串 08:30:00 表示上午8点后,然后使用时间戳记一词,避免使用持续时间一词。

If by the string 08:30:00 you mean "half-past eight in the morning", then use the word 'timestamp' and avoid the term 'duration'.

这是两个非常不同的概念。您必须对它们有所了解,每项思想都应与众不同。使用HH:MM:SS的模棱两可的格式会使区分更加困难(因此请避免使用该格式!)。

These are two very different concepts. You must get clear on them, each should be distinct in your mind. Using the ambiguous format of HH:MM:SS makes that distinction all the more difficult (so avoid that format!).

现代方法是使用java.time类。

The modern way is with the java.time classes.

如Sharma的评论中所述,首先将您的字符串解析为 LocalTime 。此类表示一天中没有日期和时区的时间。没有时区意味着这些对象基于24小时通用时钟,而不考虑诸如夏令时之类的异常时间(DST)

As mentioned in the comment by Sharma, first parse your string as a LocalTime. This class represents a time-of-day without a date and without a time zone. Having no time zone means these objects are based on a generic 24-hour clock without regard for anomalies such as Daylight Saving Time (DST).

我们真的不想要 LocalTime ,因为您的输入字符串代表一个时间跨度而不是一天中的时间。但这只是第一步。

We do not really want a LocalTime as your input string represents a span of time rather than a time-of-day. But this is just the first step.

LocalTime lt = LocalTime.parse ( "08:30:00" );



持续时间



要表示所需的时间跨度,我们需要 Duration 类。此类用于未附加到时间轴的时间跨度。我们可以通过转换 LocalTime 来创建一个时钟,方法是从一天中的时钟开始时间 00:00:00.0开始 LocalTime.MIN ,以及我们刚刚实例化的 lt

Duration

To represent the desired span-of-time, we want the Duration class. This class is for spans of time not attached to the timeline. We can create one by converting that LocalTime via getting the amount of time from the beginning of the time-of-day clock, 00:00:00.0 or LocalTime.MIN, and the lt we just instantiated.

Duration d = Duration.between ( LocalTime.MIN , lt );



ISO 8601



我们可以看到通过简单地调用 ISO 8601格式的字符串 = http://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#toString-- rel = nofollow noreferrer> Duration :: toString 。解析/生成字符串时,java.time类默认使用ISO 8601。对于持续时间,标准格式为 PnYnMnDTnHnMnS ,其中 P 标记开始,而 T 将年-月-日-天部分与小时-分钟-秒部分分开。因此,我们八个半小时将显示为 PT8H30M

ISO 8601

We can see the result by generating a String in standard ISO 8601 format for durations by simply calling Duration::toString. The java.time classes use ISO 8601 by default when parsing/generating strings. For durations, the standard format is PnYnMnDTnHnMnS where the P marks the beginning and the T separates the years-months-days portion from the hours-minutes-seconds portion. So, our eight-and-a-half hours will appear as PT8H30M.

System.out.println( d.toString(): + d);

System.out.println ( "d.toString(): " + d );


d.toString():PT8H30M

d.toString(): PT8H30M



避免使用日期时间值的十进制数字



为处理此类持续时间值,我强烈建议使用<$序列化为文本时,使用Java代码和ISO 8601格式的c $ c> Duration 对象。


  • 在代码中使用对象可提供类型安全性,使代码更具自记录性并确保有效值。

  • 使用ISO 8601格式的文本可以很容易地解析值,是人类易于阅读的格式,其含义与 08:30一样明确:00 可能会误读为一天中的某个时间。

  • Using objects in your code provides type-safety, makes your code more self-documenting, and ensures valid values.
  • Using ISO 8601 format for text makes for values that can easily be parsed, is a format easily read by humans, and is unambiguous in its meaning unlike 08:30:00 which can be misread as a time-of-day.

您想要的小数点格式像 8.5 这样的数字是模棱两可的(很容易忘记其含义)。另外,当使用浮点类型( float Float double Double ),因为这些类型在小数部分的末尾生成无关的错误数字。浮点技术特意权衡了准确性以提高执行速度。

Your desired format of a decimal number like 8.5 is ambiguous (easy to lose track of its meaning). Also a decimal number is awkward and often incorrect when using a floating-point type (float, Float, double, Double) as these types generate extraneous incorrect digits at the far end of the decimal fraction. Floating-point technology purposely trades away accuracy to gain speed of execution.

如果必须使用小数数字,并想要准确性,请使用 BigDecimal 类。

If you must use a fractional number, and want accuracy, use the BigDecimal class.

在此示例中,我假设您要截断任何小数分钟都需要小时和分钟。因此,我在 Duration 上调用 toMinutes

In this example, I assume you want hours and minutes while truncating any fractional minute. So I call toMinutes on the Duration.

BigDecimal minutesPerHour = new BigDecimal ( 60L ); // Use var/constant for clarity of your intent.
BigDecimal minutes = new BigDecimal ( d.toMinutes () );
BigDecimal fractionalHours = minutes.divide ( minutesPerHour );




fraionalHours.toString():8.5

frationalHours.toString(): 8.5

请参见以下示例在IdeOne.com中直播的代码

如果您坚持使用这些小数而不是<$,则可能要使用 BigDecimal 进行舍入。 c $ c> Duration 对象和ISO 8601文本。

You might want to use BigDecimal facility for rounding if you insist on using these decimals rather than Duration objects and ISO 8601 text.

java.time 框架。这些类取代了麻烦的旧旧版日期时间类,例如 java.util.Date Calendar ,& SimpleDateFormat

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.

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

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

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

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

从哪里获取java.time类?

Where to obtain the java.time classes?


  • Java SE 8 SE 9 和后来的


    • 内置。

    • 具有捆绑实现的标准Java API的一部分。

    • Java 9添加了一些次要功能和修复。

    • Java SE 8 and SE 9 and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.

      • 许多java.time功能都被反向移植到Java 6& nofollow noreferrer> ThreeTen-Backport

      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • See How to use ThreeTenABP….

      ThreeTen-Extra 项目使用其他类扩展了java.time。该项目为将来可能在java.time中添加内容打下了基础。您可能会在这里找到一些有用的类,例如 时间间隔 YearWeek YearQuarter 更多

      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.

      这篇关于转换时间戳字符串“ HH:mm:ss”到持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆