我有一个hh:mm:ss格式的字符串。这是一个电话通话的持续时间。
我想知道那个电话的持续时间是几秒钟。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
LocalDateTime time = LocalDateTime.parse(timeStr, formatter);如何从LocalDateTime中获得以秒为单位的持续时间?
发布于 2017-06-20 10:19:48
没有日期组件,所以您可以简单地使用一个LocalTime,尽管LocalTime 实际上并不是用来表示持续时间的。
String input = "01:52:27";
LocalTime time = LocalTime.parse(input);
int seconds = time.toSecondOfDay();请注意,这只在23:59:59之前的持续时间内起作用。
一种更好的方法是使用Duration 类--注意,它还可以处理更长的时间:
//convert first to a valid Duration representation
String durationStr = input.replaceAll("(\\d+):(\\d+):(\\d+)", "PT$1H$2M$3S");
Duration duration = Duration.parse(durationStr);
int seconds = duration.getSeconds();发布于 2017-06-20 10:14:58
没有必要将其转换为LocalDateTime,我们可以从字符串中直接得到秒数。
试着用冒号来分割它,然后得到最后一个元素。
或者,如果您正在寻找总秒,相应地乘以每个部分:
String time = "10:15:34";
String[] sections = time.split(":");
int seconds = Integer.parseInt(sections[2]);
int totalSeconds =
(Integer.parseInt(sections[0]) * 60 * 60) +
(Integer.parseInt(sections[1]) * 60) +
(Integer.parseInt(sections[2]));
System.out.println("Seconds: " + seconds);
System.out.println("Total seconds: " + totalSeconds);发布于 2017-06-20 10:14:02
不确定是否存在内置的内容,但以下内容应该完成此工作:
private long getSecondDuration(LocalDateTime t) {
long h = t.getHour();
long m = t.getMinute();
long s = t.getSecond();
return (h * 3600) + (m * 60) + s;
}https://stackoverflow.com/questions/44650075
复制相似问题