Java日期月差

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1086396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:27:21  来源:igfitidea点击:

Java Date month difference

javadate

提问by

I have start date and end date.

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

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

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

For example

例如

  • From date: 2009-01-29
  • To date: 2009-02-02
  • 从日期:2009-01-29
  • 截止日期:2009-02-02

It has one jan date and one Feb date.

它有一个一月的日期和一个二月的日期。

It should return 2.

它应该返回 2。

回答by kgiannakakis

You can use a Calendar or Joda timelibrary for this.

您可以为此使用日历或Joda 时间库。

In Joda time you can use the Days.daysBetween() method. You can then calculate the months difference. You can also use DateTime.getMonthOfYear() and do a subtraction (for dates in the same year).

在 Joda 时间,您可以使用 Days.daysBetween() 方法。然后您可以计算月差。您还可以使用 DateTime.getMonthOfYear() 并进行减法(对于同一年的日期)。

回答by Josef Pfleger

Joda Timeis a pretty cool library for Java Date and Time and can help you achieve what you want using Periods.

Joda Time是一个非常酷的 Java 日期和时间库,可以帮助您使用Periods实现您想要

回答by Brian Agnew

I would stronglyrecommend Joda-Time(and as of Java 8, the Java Time apis) for this.

为此,我强烈推荐Joda-Time(从 Java 8 开始,Java Time apis)。

  1. It makes this sort of work very easy (check out Periods)
  2. It doesn't suffer from the threading issues plaguing the current date/time objects (I'm thinking of formatters, particularly)
  3. It's the basis of the new Java date/time APIs to come with Java 7 (so you're learning something that will become standard)
  1. 它使这种工作变得非常容易(查看Periods
  2. 它不会受到困扰当前日期/时间对象的线程问题的影响(我正在考虑格式化程序,特别是)
  3. 它是 Java 7 附带的新 Java 日期/时间 API 的基础(因此您正在学习将成为标准的东西)

Note also Nick Holt's comments below re. daylight savings changes.

另请注意 Nick Holt 在下面的评论。夏令时变化。

回答by Steve Jessop

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.

正如其他人所说,如果有一个库可以为您提供几个月的时差,并且您可以使用它,那么您也可以。

Otherwise, if y1and m1are the year and month of the first date, and y2and m2are the year and month of the second, then the value you want is:

否则,如果y1m1是第一个日期的年和月,而y2m2是第二个日期的年和月,那么您想要的值是:

(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.

请注意,即使第二个日期在第一个日期之后,中间项 (m2 - m1) 也可能为负数,但这很好。

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.

月份是使用 January=0 还是 January=1 并不重要,年份是 AD、自 1900 年以来的年份或其他年份都无关紧要,只要这两个日期使用相同的基础即可。因此,例如不要混合 AD 和 BC 日期,因为没有年份 0,因此 BC 从 AD 偏移 1。

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

y1如果它们以合适的形式提供给您,您将直接从日期中获得等,或者使用日历。

回答by nightingale2k1

using joda timewould be like this (i compared how many months between today and 20/dec/2012)

使用joda 时间会是这样(我比较了今天和 20/dec/2012 之间的几个月)

import org.joda.time.DateTime ;
import org.joda.time.Months;

DateTime x = new DateTime().withDate(2009,12,20); // doomsday lol

Months d = Months.monthsBetween( new DateTime(), x);
int monthsDiff = d.getMonths();

Result: 41 months (from july 6th 2009)

结果:41 个月(从 2009 年 7 月 6 日起)

should be easy ? :)

应该很容易?:)

ps: you can also convert your date using SimpleDateFormat like:

ps:您还可以使用 SimpleDateFormat 转换您的日期,例如:

Date x = new SimpleDateFormat("dd/mm/yyyy").parse("20/12/2009");
DateTime z = new DateTime(x);

If you don't want to use Joda (for whatever reason), you can convert your date to TimeStamp and then do the differences of milli seconds between both date and then calculate back to months. But I still prefer to use Joda time for the simplicity :)

如果您不想使用 Joda(无论出于何种原因),您可以将日期转换为时间戳,然后计算两个日期之间的毫秒差异,然后再计算回月份。但为了简单起见,我仍然更喜欢使用 Joda 时间 :)

回答by Roland Tepp

Apart from using Joda time which seems to be the the favorite suggestion I'd offer the following snippet:

除了使用 Joda 时间这似乎是我最喜欢的建议之外,我还提供以下代码段:

public static final int getMonthsDifference(Date date1, Date date2) {
    int m1 = date1.getYear() * 12 + date1.getMonth();
    int m2 = date2.getYear() * 12 + date2.getMonth();
    return m2 - m1 + 1;
}

EDIT:Since Java 8, there is a more standard way of calculating same difference. See my alternative answer using JSR-310 apiinstead.

编辑:从 Java 8 开始,有一种更标准的方法来计算相同的差异。请参阅我使用 JSR-310 api 的替代答案。

回答by Rig Veda

I had to write this implementation, becoz I had custom defined periods, which i had to look for within two dates. Here you can define you custom period and put the logic, for calculation.

我必须编写这个实现,因为我有自定义定义的时间段,我必须在两个日期内查找。您可以在此处定义自定义期间并放置逻辑以进行计算。

Here TimePeriod is a POJO which has start, end, period start, period End

这里 TimePeriod 是一个 POJO,它有开始、结束、期间开始、期间结束

public class Monthly extends Period {

public class 每月扩展 Period {

public int getPeriodCount(String startDate, String endDate, int scalar) {
    int cnt = getPeriods(startDate, endDate, scalar).size();        
    return cnt;
}

public List getPeriods(String startDate, String endDate, int scalar) {

    ArrayList list = new ArrayList();

    Calendar startCal = CalendarUtil.getCalendar(startDate);
    Calendar endCal =  CalendarUtil.getCalendar(endDate);

    while (startCal.compareTo(endCal) <= 0) {
        TimePeriod period = new TimePeriod();
        period.setStartDate(startCal.getTime());
        period.setPeriodStartDate(getPeriodStartDate((Calendar) startCal.clone()).getTime());
        Calendar periodEndCal = getPeriodEndDate((Calendar) startCal.clone(), scalar);
        period.setEndDate(endCal.before(periodEndCal) ? endCal.getTime()    : periodEndCal.getTime());
        period.setPeriodEndDate(periodEndCal.getTime());

        periodEndCal.add(Calendar.DATE, 1);
        startCal = periodEndCal;
        list.add(period);
    }

    return list;
}


private Calendar getPeriodStartDate(Calendar cal) {     
    cal.set(Calendar.DATE, cal.getActualMinimum(Calendar.DATE));        
    return cal;
}

private Calendar getPeriodEndDate(Calendar cal, int scalar) {

    while (scalar-- > 0) {
        cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
        if (scalar > 0)
            cal.add(Calendar.DATE, 1);          
    }

    return cal;
}

}

}

回答by Batuhan B

it is not the best anwer but you can use unixtimestamp First you find the unixtime's of the dates then eject each other

这不是最好的答案,但您可以使用 unixtimestamp 首先找到日期的 unixtime,然后相互弹出

Finally you should convert the unixtime(sum) to String

最后,您应该将 unixtime(sum) 转换为 String

回答by lory105

That's because the classes JavaDate and Calendar use the Month indices from 0-11

那是因为类JavaDate 和 Calendar 使用来自的 Month 索引0-11

January = 0
December = 1

Is recommended to use Joda Time!

推荐使用Joda Time

回答by Uncle Iroh

Based on the above suggested answers I rolled my own which I added to my existing DateUtils class:

根据上述建议的答案,我推出了自己的答案,并将其添加到现有的 DateUtils 类中:

    public static Integer differenceInMonths(Date beginningDate, Date endingDate) {
        if (beginningDate == null || endingDate == null) {
            return 0;
        }
        Calendar cal1 = new GregorianCalendar();
        cal1.setTime(beginningDate);
        Calendar cal2 = new GregorianCalendar();
        cal2.setTime(endingDate);
        return differenceInMonths(cal1, cal2);
    }

    private static Integer differenceInMonths(Calendar beginningDate, Calendar endingDate) {
        if (beginningDate == null || endingDate == null) {
            return 0;
        }
        int m1 = beginningDate.get(Calendar.YEAR) * 12 + beginningDate.get(Calendar.MONTH);
        int m2 = endingDate.get(Calendar.YEAR) * 12 + endingDate.get(Calendar.MONTH);
        return m2 - m1;
    }

And the associatiated unit tests:

以及相关的单元测试:

    public void testDifferenceInMonths() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        assertEquals(12, DateUtils.differenceInMonths(sdf.parse("2014/03/22"), sdf.parse("2015/03/22")).intValue());

        assertEquals(11, DateUtils.differenceInMonths(sdf.parse("2014/01/01"), sdf.parse("2014/12/25")).intValue());

        assertEquals(88, DateUtils.differenceInMonths(sdf.parse("2014/03/22"), sdf.parse("2021/07/05")).intValue());

        assertEquals(6, DateUtils.differenceInMonths(sdf.parse("2014/01/22"), sdf.parse("2014/07/22")).intValue());
    }