两个日期之间的星期Java + Joda时间 [英] Week between two dates Java + Joda Time

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

问题描述

我想获取Java中两个日期范围之间的周数和月数.例如开始日期:2012/03/01结束日期:2012年3月5日

I wanted to get the number of weeks and months between two date range in Java. For ex., Start Date: 03/01/2012 End Date: 03/05/2012

由于两个日期分别位于两个不同的星期,所以我希望结果为2而不是0.

Since the two dates fall in two different weeks I want the result to be 2 instead of 0.

问题的第二部分是:开始日期:02/29/2012结束日期:2012年3月1日

Second part of the problem is: Start Date: 02/29/2012 End Date: 03/01/2012

之间的月份数应为2.

我一直在网上搜索有关此内容,许多人建议在Java中使用Joda Date时间.所以我试了一下.我本来可以工作几周,但是我不确定这是否是正确的方法.这是我要获取一周时间的方法:

I have been searching online regarding this and lot of people have recommended using Joda Date time in Java. So I gave it a shot. I was able to get the weeks working but I am not sure if this is the right way. Here is what I am doing to get the week duration:

    DateTime s = new DateTime(Long.parseLong("1330573027000")); // 2012-02-29
    DateTime e = new DateTime(Long.parseLong("1331005027000")); // 2012-03-05   

    Weeks weeks = Weeks.weeksBetween(s, e).plus(1);

当我期望2时,这将返回1,因为两个日期在不同的星期中.

This returns 1, when I am expecting 2 since two dates are in different weeks.

对于几个月的持续时间,我尝试遵循相同的方法,但是它返回0,但是我希望它返回2,因为两个日期是在两个不同的月份中.

For months duration I tried to follow the same but it returns 0 but I want it to return 2 since the two dates are in two different months.

有人可以指出正确的方向吗?

Could someone please point me in right direction?

谢谢!

修改:我想我有一种方法,请让我知道它是否正确:

I think I got one way of doing it, please let me know if it looks right:

    DateTime start = new DateTime(Long.parseLong("1330659427000"));
    DateTime start = new DateTime(Long.parseLong("1331005027000"));

    DateTime finalStart = start.dayOfWeek().withMinimumValue();
    DateTime finalEnd   = end.dayOfWeek().withMaximumValue();

然后获取finalStart和finalEnd之间的区别.这看起来正确吗?

And then get the difference between finalStart and finalEnd. Does this looks correct?

Edit2 更新了结束时间

推荐答案

JodaTime Weeks.weeksBetween(s,e)仅返回整周计数.不完整的周数不计算在内.要解决此问题,您必须保证日子在一周的开始和结束.试试这个:

JodaTime Weeks.weeksBetween(s, e) returns only whole week count. Incomplete weeks are not counted. To resolve this, you must garantee that the days are at the start and at the end of the week. Try this:

int weeks = Weeks.weeksBetween(s.dayOfWeek().withMinimumValue().minusDays(1), 
            e.dayOfWeek().withMaximumValue().plusDays(1)).getWeeks();

minusDays/plusDays将保证我要计算的周数已满.

The minusDays/plusDays will garantee that the weeks i'm trying to count are full.

相同的逻辑适用于月份:

Same logic apply for Months:

int months = Months.monthsBetween(s.dayOfMonth().withMinimumValue().minusDays(1),
             e.dayOfMonth().withMaximumValue().plusDays(1)).getMonths();

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

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