Java日期月差 [英] Java Date month difference

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

问题描述

我有开始日期和结束日期。

I have start date and end date.

我需要java中这两个日期之间的月份数。

I need the number of months between this two dates in java.

例如,
从日期:29-01-2009
到目前为止:02-02-2009

For eg, from date:29-01-2009 to date :02-02-2009

(它有jan日期和二月日期)。

(It has jan date and Feb date).

应该返回2。

推荐答案

其余的说,如果有一个图书馆会给你几个月的时间差异,你可以使用它,那么你也可以这样做。

As the rest say, if there's a library that will give you time differences in months, and you can use it, then you might as well.

否则,如果 y1 m1 是第一个日期的年份和月份, y2 m2 是第二年的年份,那么你想要的价值是:

Otherwise, if y1 and m1 are the year and month of the first date, and y2 and m2 are the year and month of the second, then the value you want is:

(y2 - y1) * 12 + (m2 - m1) + 1;

在第一个之后,但是没关系。

Note that the middle term, (m2 - m1), might be negative even though the second date is after the first one, but that's fine.

无论月份是在1月= 0还是1月= 1,都不重要,无论是否年是AD,自1900年以来,或任何,只要两个日期都使用相同的基础。所以例如不要混合AD和BC日期,因为没有一年0,因此BC被AD偏移1。

It doesn't matter whether months are taken with January=0 or January=1, and it doesn't matter whether years are AD, years since 1900, or whatever, as long as both dates are using the same basis. So for example don't mix AD and BC dates, since there wasn't a year 0 and hence BC is offset by 1 from AD.

你会得到 y1 等等,从日期直接如果以合适的形式提供给您,或使用日历。

You'd get y1 etc. either from the dates directly if they're supplied to you in a suitable form, or using a Calendar.

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

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