Java:跨越几个月的两个日期之间的差异 [英] Java: Difference between two dates spanning over months

查看:203
本文介绍了Java:跨越几个月的两个日期之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以成功获取两天之间的差异(以天,小时,分钟,秒为单位):

I have the following code that successfully gets me the difference between two days (in days, hours, minutes, seconds):

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
Date d1 = format.parse(startTime);
Date d2 = format.parse(endTime);
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Start: " + startTime);
System.out.println("End: " + endTime);
System.out.println(diffDays + " days, " + diffHours + " hours, " + diffMinutes + " minutes, " + diffSeconds + " seconds");

但是,当日期跨越另一个月时,这不起作用,例如:

However, this does not work when the dates cross into another month, for example:

Start: 2013-07-31 10:15:01
End: 2013-08-01 11:22:33
-29 days, -22 hours, -52 minutes, -28 seconds

Start: 2013-05-31 10:15:01
End: 2013-08-01 11:22:33
-29 days, -22 hours, -52 minutes, -28 seconds

是否可以智能地跨越数月并获得准确的时差?我对Joda很熟悉,但是我想坚持使用标准的Java API,除非没有像Joda这样的东西是不可能的。

Is it possible to intelligently span over months and get accurate time differences? I am familiar with Joda but would like to stick with standard Java APIs unless this is not possible without something like Joda.

推荐答案

你正在使用

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");

应该是

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

你会得到正确的结果

Start: 2013-05-31 10:15:01
End: 2013-08-01 11:22:33
62 days, 1 hours, 7 minutes, 32 seconds

这是日期模式的javadoc。 dd 是按月计算的。 DD 是一年中的一天。您的日期对象未按预期方式解析。基本上, 31 的日期值覆盖了月份值。

Here's the javadoc for the date patterns. dd is day in month. DD is day in year. Your Date objects just weren't parsed the way you expected. Basically the day in year value of 31 was overwriting the month value.

调试器是你的朋友。

这篇关于Java:跨越几个月的两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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