问题
我有三个日期作为字符串对象,格式为:dd:HH:mm:ss
00:1:9:14
00:3:10:4
00:3:39:49
如何在 Java 中添加这些日期以获得总和( 00:7:59:07 )?
示例代码:
- SimpleDateFormat sdf = new SimpleDateFormat("dd:HH:mm:ss");
- Date d1 = sdf.parse("00:1:9:14");
- Date d2 = sdf.parse("00:3:10:4");
- Date d3 = sdf.parse("00:3:39:49");
- System.out.println(d1);
- System.out.println(d2);
- System.out.println(d3);
- Date d = new Date(d1.getTime() + d2.getTime() + d3.getTime());
- System.out.println(d);
复制代码
输出(错误):
- Wed Dec 31 01:09:14 IST 1969
- Wed Dec 31 03:10:04 IST 1969
- Wed Dec 31 03:39:49 IST 1969
- Sun Dec 28 20:59:07 IST 1969
复制代码
回答
dd 格式包括月份中的日期。因此,如果您使用 00 (或 Java SimpleDateFormat ,因为它还包括月份中的哪一天),您的 Date 值将下溢。相反,分析您的时间部分并自己进行计算。
例如,您可以使用 TimePart 、 days 、 hours 、 minutes 和 seconds 创建一个类
- static class TimePart {
- int days = 0;
- int hours = 0;
- int minutes = 0;
- int seconds = 0;
- static TimePart parse(String in) {
- if (in != null) {
- String[] arr = in.split(":");
- TimePart tp = new TimePart();
- tp.days = ((arr.length >= 1) ? Integer.parseInt(arr[0]) : 0);
- tp.hours = ((arr.length >= 2) ? Integer.parseInt(arr[1]) : 0);
- tp.minutes = ((arr.length >= 3) ? Integer.parseInt(arr[2]) : 0);
- tp.seconds = ((arr.length >= 4) ? Integer.parseInt(arr[3]) : 0);
- return tp;
- }
- return null;
- }
- public TimePart add(TimePart a) {
- this.seconds += a.seconds;
- int of = 0;
- while (this.seconds >= 60) {
- of++;
- this.seconds -= 60;
- }
- this.minutes += a.minutes + of;
- of = 0;
- while (this.minutes >= 60) {
- of++;
- this.minutes -= 60;
- }
- this.hours += a.hours + of;
- of = 0;
- while (this.hours >= 24) {
- of++;
- this.hours -= 24;
- }
- this.days += a.days + of;
- return this;
- }
- @Override
- public String toString() {
- return String.format("%02d:%02d:%02d:%02d", days, hours, minutes,
- seconds);
- }
- }
复制代码
那么你的测试用例
- public static void main(String[] args) {
- try {
- TimePart d1 = TimePart.parse("00:1:9:14");
- TimePart d2 = TimePart.parse("00:3:10:4");
- TimePart d3 = TimePart.parse("00:3:39:49");
- System.out.println(d1);
- System.out.println(d2);
- System.out.println(d3);
- TimePart d4 = d1.add(d2).add(d3);
- System.out.println(d4);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
复制代码
它似乎正确地执行了加法,比如
- 00:01:09:14
- 00:03:10:04
- 00:03:39:49
- 00:07:59:07
复制代码
|