在Joda-Time的两个日期之间的天数 [英] Number of days between two dates in Joda-Time

查看:98
本文介绍了在Joda-Time的两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查找两个 Joda-Time 之间的天数差异 DateTime 实例?
天数差异我的意思是说,如果开始是星期一,结束是在星期二我预计返回值为1,不管开始和结束日期的小时/分/秒。



Days.daysBetween(开始,结束).getDays()如果开始是在晚上结束,给我0 / p>

我也和其他日期字段有同样的问题,所以我希望有一个通用的方式来忽略不那么重要的字段。



换句话说,3月2日至4日之间的月份也将是1,14时45分至15时12分之间的时间。但是,14:01和14:55之间的小时差将为0。

解决方案

令人痛心的是,withTimeAtStartOfDay答案是错误的,但是只有偶尔。你想要:

  Days.daysBetween(start.toLocalDate(),end.toLocalDate())。getDays()

事实证明,午夜/开始的一天有时意味着上午1点(在某些地方这样做是夏令时的事情) ,哪些Days.daysBetween不能正常处理。

  // 2013年10月21日20日下午1点,巴西
DateTimeZone BRAZIL = DateTimeZone.forID(America / Sao_Paulo);
DateTime start = new DateTime(2013,10,20,5,0,0,BRAZIL);
DateTime end = new DateTime(2013,10,21,13,0,0,BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
end.withTimeAtStartOfDay())。getDays());
// print 0
System.out.println(daysBetween(start.toLocalDate(),
end.toLocalDate())。getDays());
// print 1

通过 LocalDate 回避整个问题。


How do I find the difference in Days between two Joda-Time DateTime instances? With ‘difference in days’ I mean if start is on Monday and end is on Tuesday I expect a return value of 1 regardless of the hour/minute/seconds of the start and end dates.

Days.daysBetween(start, end).getDays() gives me 0 if start is in the evening and end in the morning.

I'm also having the same issue with other date fields so I was hoping there would be a generic way to 'ignore' the fields of lesser significance.

In other words, the months between Feb and 4 March would also be 1, as would the hours between 14:45 and 15:12 be. However the hour difference between 14:01 and 14:55 would be 0.

解决方案

Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:

Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()

It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.

// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
                               end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
                               end.toLocalDate()).getDays());
// prints 1

Going via a LocalDate sidesteps the whole issue.

这篇关于在Joda-Time的两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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