英文:
convert string Time to Time Object Java "Text could not be parsed at index 0"
问题
我有以下的字符串格式:"0小时:5分钟:21秒"。
我需要将其转换为格式:"hh:mm:ss",以便能够计算列表中总小时数。
我正在使用以下代码:
DateTimeFormatter parser = DateTimeFormatter.ofPattern("hh '小时' : mm '分钟' : ss '秒'", Locale.US);
LocalDate odt = LocalDate.parse(k, parser);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String printDate = formatter.format(odt);
System.out.println(printDate);
但是它给我一个错误消息:"无法解析文本 '0小时:5分钟:321秒',索引位置为0"。
这个错误发生在这一行:LocalDate odt = LocalDate.parse(k, parser);
英文:
I have the following String Format "0 hours : 5 mins : 21 secs".
I need to convert into the format: "hh:mm:ss", So i would be able to calculate the sum of total hours in a list.
I am using the following
DateTimeFormatter parser = DateTimeFormatter.ofPattern("hh 'hours' : mm 'mins' : ss 'secs'", Locale.US);
LocalDate odt = LocalDate.parse(k, parser);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String printDate = formatter.format(odt);
System.out.println(printDate);
But It gives me an error : "Text '0 hours : 5 mins : 321 secs' could not be parsed at index 0".
This mistake happens on line: LocalDate odt = LocalDate.parse(k, parser);
答案1
得分: 0
如果您有这样的字符串,也许更容易创建自己的解析器:
int totalHours = 0;
// 演示时间字符串
String[] stringTimes = {"0 hours : 5 mins : 43 secs",
"2 hours : 25 mins : 31 secs",
"1 hours : 06 mins : 14 secs",
"4 hours : 43 mins : 57 secs"};
// 遍历数组中包含的所有演示时间字符串。
for (String strgTime : stringTimes) {
/* 将当前时间字符串解析为小时、分钟、秒(不区分大小写)。 */
String[] timeParts = strgTime.trim().split("(?i)\\s+hours\\s+:\\s+|\\s+mins\\s+:\\s+|\\s+secs\\s+");
/* 验证 timeParts[] 中索引为 0 的分割元素,它应该是小时部分,
是否确实是整数值的字符串表示。 */
if (timeParts[0].matches("\\d+")) {
/* 是的,它是整数值的字符串表示。
将此字符串值转换为整数类型,并添加到 totalHours 中。 */
totalHours += Integer.valueOf(timeParts[0]);
}
}
// 在控制台中显示总小时数
System.out.println("Total Hours:\t" + totalHours + " Hours");
运行后,您应该在控制台窗口中看到:Total Hours: 7 Hours
。如果删除注释和演示时间字符串数组,您会发现实际上代码并不是很多。
英文:
If you have a string like that then perhaps it's just easier to create your own parser:
int totalHours = 0;
// Demo time Strings
String[] stringTimes = {"0 hours : 5 mins : 43 secs",
"2 hours : 25 mins : 31 secs",
"1 hours : 06 mins : 14 secs",
"4 hours : 43 mins : 57 secs"};
// Iterate through all the demo time strings contained in array.
for (String strgTime : stringTimes) {
/* Parse the current time string into hour, minutes, seconds
(Letter case is ignored). */
String[] timeParts = strgTime.trim().split("(?i)\\s+hours\\s+:\\s+|\\s+mins\\s+:\\s+|\\s+secs\\s+");
/* Validate the fact that the split element at index 0 of
timeParts[] which is to hold hours is indeed a string
representation of a Integer value. */
if (timeParts[0].matches("\\d+")) {
/* Yes, It is a string representation of a Integer value.
Convert this String value to Integer type and add it
to totalHours. */
totalHours += Integer.valueOf(timeParts[0]);
}
}
// Display Total Hours in console
System.out.println("Total Hours:\t" + totalHours + " Hours");
After running this you should see in the Console Window: Total Hours: 7 Hours
. If you remove the comments and the demo string times array, you can see it really isn't very much code.
答案2
得分: 0
## java.time.Duration 代表时间段
我理解 `0 小时 : 5 分钟 : 312 秒` 是一个时间段(相当于 10 分钟 12 秒或总共 612 秒)。它不是一天中的特定时间。如果是这样,正确的类别是 `Duration`。(`LocalTime` 用于表示一天中的某个时间,例如 00:10:12 表示午夜过去了 10 分钟 12 秒。)
不幸的是,java.time 包中没有包含解析任意时间段字符串的机制。`Duration` 类可以解析 ISO 8601 格式的时间段字符串,仅限于此格式。幸运的是,对于大多数格式,你可以通过使用正则表达式将你所拥有的时间段字符串转换为 ISO 8601 格式。对于你的情况也是如此。
ISO 8601 格式的时间段表示方式在你适应之前可能会有些特殊。它的格式为 `PT0H5M312S`,可以理解为 *一个持续时间,持续了 0 小时 5 分钟 312 秒*。
```java
String amountOfTimeAsString = "0 小时 : 5 分钟 : 312 秒";
String iso8601String = "PT" + amountOfTimeAsString.replaceAll(
"(\\d+)\\s*(h)ours?\\s*:\\s*(\\d+)\\s*(m)ins?\\s*:\\s*(\\d+)\\s*(s)ecs?",
"$1$2$3$4$5$6");
Duration dur = Duration.parse(iso8601String);
System.out.println(dur);
输出也是 ISO 8601 格式:
> PT10M12S
表示持续时间为 10 分钟 12 秒。
Duration
类提供了 plus
方法,用于将不同的时间段相加。这听起来符合你需要将时间段相加的需求。要从总和中获取小时数,可以使用 toHours
方法。
<details>
<summary>英文:</summary>
## java.time.Duration for an amount of time
I take it that `0 hours : 5 mins : 312 secs` is an amount of time (equal to 10 minutes 12 seconds or a total of 612 seconds). It’s not a time of day. If so, the correct class to use is `Duration`. (`LocalTime` is for at time of day such as 00:10:12 when this signifies 10 minutes 12 seconds past midnight.)
Unfortunately java.time doesn’t include any mechanism for parsing arbitrary duration strings. The `Duration` class can parse duration strings in ISO 8601 format, and that’s it. Fortunately, for most formats it’s manageable to convert the duration string that you’ve got into ISO 8601 using a regular expression. This is so in your case too.
ISO 8601 format for durations is a bit peculiar until you get used to it. It goes like `PT0H5M312S`. Think of it as *a period of time of 0 hours 5 minutes 312 seconds*.
String amountOfTimeAsString = "0 hours : 5 mins : 312 secs";
String iso8601String = "PT" + amountOfTimeAsString.replaceAll(
"(\\d+)\\s*(h)ours?\\s*:\\s*(\\d+)\\s*(m)ins?\\s*:\\s*(\\d+)\\s*(s)ecs?",
"$1$2$3$4$5$6");
Duration dur = Duration.parse(iso8601String);
System.out.println(dur);
Output is in ISO 8601 format too:
> PT10M12S
A period of time of 10 minutes 12 seconds.
A `Duration` has a `plus` method for adding durations together. It sounds like what you need for summing them up. For getting the hours out of the sum use the `toHours` method.
</details>
# 答案3
**得分**: -1
你需要使用 `LocalTime` 而不是 `LocalDate`,且你的输入格式有错误。
以下是我的测试结果。
00:05:43
02:25:31
01:06:14
04:43:57
以下是我使用的可运行示例代码。感谢 @DevilsHnd 提供的输入 `String` 数组。
```java
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class DurationConversion {
public static void main(String[] args) {
String[] stringTimes = { "0 hours : 5 mins : 43 secs",
"2 hours : 25 mins : 31 secs",
"1 hours : 06 mins : 14 secs",
"4 hours : 43 mins : 57 secs" };
DateTimeFormatter parser = DateTimeFormatter.ofPattern(
"H 'hours :' m 'mins :' s 'secs'", Locale.US);
for (String k : stringTimes) {
LocalTime odt = LocalTime.parse(k, parser);
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("HH:mm:ss");
String printDate = formatter.format(odt);
System.out.println(printDate);
}
}
}
英文:
You needed to use a LocalTime
instead of a LocalDate
, and your input format had errors.
Here are my test results.
00:05:43
02:25:31
01:06:14
04:43:57
Here's the runnable example code I used. Thanks to @DevilsHnd for the input String
array.
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class DurationConve3rsion {
public static void main(String[] args) {
String[] stringTimes = { "0 hours : 5 mins : 43 secs",
"2 hours : 25 mins : 31 secs",
"1 hours : 06 mins : 14 secs",
"4 hours : 43 mins : 57 secs" };
DateTimeFormatter parser = DateTimeFormatter.ofPattern(
"H 'hours :' m 'mins :' s 'secs'", Locale.US);
for (String k : stringTimes) {
LocalTime odt = LocalTime.parse(k, parser);
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("HH:mm:ss");
String printDate = formatter.format(odt);
System.out.println(printDate);
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论