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

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

问题描述

我如何找到两个 Joda-Time DateTime 实例?对于天数差异",我的意思是如果开始是星期一,结束是星期二,无论开始日期和结束日期是多少小时/分钟/秒,我都希望返回值为 1.

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() 如果开始在晚上并且在早上结束,则给我 0.

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.

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

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.

推荐答案

恼人的是,withTimeAtStartOfDay 答案是错误的,但只是偶尔.你想要:

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

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

事实证明,午夜/一天的开始"有时意味着凌晨 1 点(夏令时在某些地方会发生这种情况),而 Days.daysBetween 无法正确处理.

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

通过 LocalDate 绕过整个问题.

Going via a LocalDate sidesteps the whole issue.

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

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