获取日期date1和date2之间的月份数量

时间:2013-12-21 23:23:01

标签: java android date gregorian-calendar

我有两个约会。想要在DOD和DDO之间获得数月的数量。 如果我在for循环中这样做最好,增加每个月的日期。 我需要所有月份,它们在date1和date2之间。

例如,当我有一个日期:d1 = 2013-07-28,d2 = 2013-09-02 我想得到3(到7月,8月和9月)。

String przekazaneDataOd = "2013-10-26" ; 
String przekazaneDataDo = "2014-03-11" ;

SimpleDateFormat dfIn = new SimpleDateFormat("yyyy-MM-dd");

Date d1 = null;
Date d2 = null;
try {
    d1=dfIn.parse(przekazaneDataOd);
    d2=dfIn.parse(przekazaneDataDo);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

GregorianCalendar DOD = new GregorianCalendar();
DOD.setTime(d1);

GregorianCalendar DDO = new GregorianCalendar();
DDO.setTime(d2);

2 个答案:

答案 0 :(得分:1)

日期时间库

一个很好的日期时间库,例如:

...使这种工作更加更容易,更强可靠

Joda-Time示例

在Joda-Time 2.3中,基本上只有一行代码...... Months.monthsBetween( start, stop )

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

String przekazaneDataOd = "2013-10-26" ;
String przekazaneDataDo = "2014-03-11" ;

DateTime start = new DateTime( przekazaneDataOd );
DateTime stop = new DateTime( przekazaneDataDo );

// Exclusive of the months of the dates. Just the full months *between* the dates.
Months monthsBetween = Months.monthsBetween( start, stop );
int monthsNumber = monthsBetween.getMonths();

// Inclusive of the months of the dates.
DateTimeZone timeZone_Warsaw = DateTimeZone.forID("Europe/Warsaw" );
// Get first day of the month containing start date.
DateTime outside_begin = new DateTime( przekazaneDataOd, timeZone_Warsaw ).withDayOfMonth( 1 ).withTimeAtStartOfDay();
// Get first day of the month *after* the month containing the stop date.
DateTime outside_end = new DateTime( przekazaneDataDo, timeZone_Warsaw ).plusMonths(1).withDayOfMonth( 1 ).withTimeAtStartOfDay();
int outside_months = Months.monthsBetween( outside_begin, outside_end ).getMonths();

转储到控制台...

System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
System.out.println( "monthsNumber: " + monthsNumber );

System.out.println( "outside_begin: " + outside_begin );
System.out.println( "outside_end: " + outside_end );
System.out.println( "outside_months: " + outside_months );

跑步时......

start: 2013-10-26T00:00:00.000-07:00
stop: 2014-03-11T00:00:00.000-07:00
monthsNumber: 4
outside_begin: 2013-10-01T00:00:00.000+02:00
outside_end: 2014-04-01T00:00:00.000+02:00
outside_months: 6

CAVEAT 通常,更好的做法是始终指定named time zone,例如 Europe / Warsaw 。 (将DateTimeZone实例传递给DateTime的构造函数。)但在这种情况下,时区可能无关紧要,但我不确定。请注意,在 Inclusive 代码块中,我包含了一个时区。该区域是 Warsaw ,因为Google称przekazane是波兰语。

答案 1 :(得分:0)

试试这个:

int m = DDO.get(Calendar.MONTH) - DOD.get(Calendar.MONTH);
if(!DOD.before(DDO)) m = -m;
int y = Math.abs(DOD.get(Calendar.YEAR) - DDO.get(Calendar.YEAR));
if(y > 0){
    return 12*y+m;
}
else if(y == 1 && m == 0){
    return 12;
}
else{
    return m;
}