如何在Java中存储花费的时间或总持续时间? [英] How to store time spent or total duration in Java?

查看:129
本文介绍了如何在Java中存储花费的时间或总持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用POI API for Java自动化excel报告.我将使用POI阅读,处理这些报告并创建一个新的excel报告.

excel文件中的一列已花费了总时间,也就是说,它可能采用以下格式,即 46:23:12 -读取时间为 46小时23分钟12秒.

我了解如何读取日期和时间值,通常将它们存储在 java.util.Date 中.这里的问题是这是一个持续时间,花费的时间可能超过24小时.哪种数据类型适合于此?以及如何使用POI阅读此内容?

解决方案

在Java 8中,

duration 对象将包含与输入相等的数量(在这种情况下:46小时23分钟12秒).如果您调用 duration.toString(),它将在 ISO 8601中返回此持续时间格式:

PT46H23M12S


当然,此代码假定输入 String 始终包含三个字段(小时,分钟和秒).但是您可以在解析值之前检查 values.length (并且仅在各自的值不为零时,才调用 plus 方法).


如果您使用的是 Java< = 7 ,则可以使用 ThreeTenBackport ,这是Java 8的新日期/时间类的绝佳反向端口.对于 Android ,有一个 ThreeTenABP (有关如何使用它的更多信息此处).

唯一的区别是软件包名称(在Java 8中是 java.time ,在ThreeTen Backport(或Android的ThreeTenABP)中是 org.threeten.bp ),但是类和方法的名称是相同的.

I am automating a excel report using the POI API for Java. I will have few reports in my disposal which I read using POI, process them, and create a new excel report.

One of columns from an excel file has total time spent, that is, it could in following format, 46:23:12 - this reads as 46 hours, 23 minutes and 12 seconds.

I understand how to read date and time values and I usually store them in java.util.Date. The problem here is this is a time duration, the hours spent could be more than 24. Which datatype could be suitable for this? And how do I read this using POI?

解决方案

In Java 8, an amount of time is represented by the class java.time.Duration.

I'm not sure if Apache POI has methods to deal directly with a Duration, so I believe that the best approach is to get the value as String, then parse this String to get the values and add those values to the Duration:

String s = "46:23:12";
String[] values = s.split(":");
// get the hours, minutes and seconds value and add it to the duration
Duration duration = Duration.ofHours(Integer.parseInt(values[0]));
duration = duration.plusMinutes(Integer.parseInt(values[1]));
duration = duration.plusSeconds(Integer.parseInt(values[2]));

The duration object will contain the amount equivalent to the input (in this case: 46 hours, 23 minutes and 12 seconds). If you call duration.toString(), it returns this duration in ISO 8601 format:

PT46H23M12S


Of course this code assumes that the input String always contains the three fields (hours, minutes and seconds). But you could check for values.length before parsing the values (and also call the plus methods only if the respective value is not zero).


If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.

这篇关于如何在Java中存储花费的时间或总持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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