-2

I'm new to Java. What I want is when I pass the start date and the end date to a function as parameters I want to get the number of days, number of months and number of years between the start and the end date.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user421607
  • 175
  • 2
  • 4
  • 12

2 Answers2

3

If you use JodaTime, it's simple:

DateTime start = // your start date
DateTime end = // your end date
int days = Days.daysBetween(start, end).getDays();
int months = Months.monthsBetween(start, end).getMonths();
int years = Years.yearsBetween(start, end).getYears();
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
0

tl;dr

Period.between( 
    LocalDate.of( 2011 , 1 , 1) , 
    LocalDate.now( ZoneId.of( "America/Montreal" ) ) 
).toString();  // Example: P5Y4M2D

java.time

The Answer by Floyd is correct but outdated. The Joda-Time project is in maintenance mode, with its team advising migration to the java.time classes.

LocalDate

The LocalDate class represents a date without a time-of-day and without a time zone.

LocalDate start = LocalDate.of( 2011 , 1 , 1 );
LocalDate stop = LocalDate.of( 2016 , 1 , 15 );

ChronoUnit

The ChronoUnit class calculates elapsed time.

long elapsedInYears = ChronoUnit.YEARS.between( start , stop );
long elapsedInMonths = ChronoUnit.MONTHS.between( start , stop );
long elapsedInDays = ChronoUnit.DAYS.between( start , stop );

Period

If you want one span of time broken out as a number of years and a number of months and a number of days, then use the Period class.

Period p = Period.between( start , stop );

To get the handy standard ISO 8601 formatted String representation, call toString. The format is PnYnMnDTnHnMnS where the P marks the beginning and the T separates years-months-days from the hours-minutes-seconds. So a month and a half would be P1M15D.

String output = p.toString(); 

If you want each part as a number, call getter methods.

int years = p.getYears();
int months = p.getMonths();
int days = p.getDays();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154