如何使用Java的Joda API在几个月内计算差异 [英] How to calculate difference ONLY in months using Java's Joda API

查看:328
本文介绍了如何使用Java的Joda API在几个月内计算差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,它只是计算2个给定日期之间的月份,并将该值返回给程序。例如,如果我必须计算4月1日至6月30日(这是一个季度,3个月)之间的月数,我使用以下代码:

I am writing a program that is supposed to just calculate the months between 2 given dates and return the value to the program. For instance, if I have to calculate the number of months between 1 April and 30 June (which is a quarter, 3 months), and I use the following code:

    DateTime start = new DateTime().withDate(2011, 4, 1);
    DateTime end = new DateTime().withDate(2011, 6, 30);

    Months mt = Months.monthsBetween(start, end);
    int monthDiff = mt.getMonths();

使用这个,我仍然以2为月数,而实际上是 3个月。这是我想要的一个例子。我只计算月数(即从结束月份的最后一个月的起始月份的第1个月起),我不需要像天,周,小时等等额外的分析。如何实现这一点?

Using this, I am still getting "2" as the number of months, whereas it is actually "3" months. This is an example of what I want. I am only calculating the number of months (i.e. from 1st of the start month t the last date of the end month) and I dont need additional analysis like days, weeks, hours, etc. How do I achieve this?

任何帮助将不胜感激。

Any help would be appreciated.

推荐答案

DateTime start = new DateTime().withDate(2011, 4, 1);
DateTime end = new DateTime().withDate(2011, 6, 30);
Period p = new Period(start, end, PeriodType.months().withDaysRemoved());
int months = p.getMonths() + 1;

您需要 withDaysRemoved()确保增加一个月数月的工作。否则两个日期,如 2011-04-15 2011-06-14 仍然会导致答案为 2

You need the withDaysRemoved() part to ensure that adding one to the number of months works. Otherwise two dates such as 2011-04-15 and 2011-06-14 would still result in the answer being 2

这篇关于如何使用Java的Joda API在几个月内计算差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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