Date-Time Library
A good date-time library such as:
…makes this kind of work much easier and more reliable.
Joda-Time Example
In Joda-Time 2.3, basically one line of code… 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();
Dump to console…
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 );
When run…
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 Generally, a better practice is to always specify a named time zone such as Europe/Warsaw. (Pass a DateTimeZone instance to constructor of DateTime.) But in this case, time zones may not matter, but I'm not sure. Note that in the Inclusive chunk of code, I included a time zone. The zone is Warsaw because The Google says przekazane
is Polish.