-1

I am developing an android App.

I would like to know how to calculate exact number of "years, months and days" between two dates.

e.g. 1. "2014.1.3" to "2015.1.4" →Answer: "1 year and 1 day"

  1. "2013.1.3" to "2014.4.2" →Answer: "1 year and 2 months and 30 days"

I think iPhone app has this class "NSDateComponent(NSYearCalendarUnit,NSMonthCalendarUnit,NSDayCalendarUnit)", but it seems not for the Android.

Is there any effective way in android?

supermonkey
  • 631
  • 11
  • 25
  • There is the Java calender API. See this: http://www.mkyong.com/java/java-date-and-calendar-examples/ and this: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html – Alex K Nov 30 '14 at 15:16
  • Thank you for your reply. I know calendar API, but I have no idea about how to solve the above question with the API. Could you tell me sample codes? – supermonkey Nov 30 '14 at 15:48
  • I could. But it would be so much easier for both of us if you used google and found the hundreds of thousands of examples already out there. – Alex K Nov 30 '14 at 15:58
  • I think it is not so easy. For example, must take leap year into account. Calculating only difference of days is easy, but calculating the difference with a format of "years and months and days" is tiresome. I would like to find an effective easy way. – supermonkey Nov 30 '14 at 16:54

1 Answers1

1

If I were you I would use subtrings to split each year, month and day into strings using the "."s as guides

year1String = date.substring(0,4);
month1String = date.substring(5,6);
day1String = date.substring(7,8);

year2String = date.substring(0,4);
month2String = date.substring(5,6);
day2String = date.substring(7,8);

and then convert those strings into integers (say year1, year2, month1, month2, day1 and day2). Then I would just do basic subtraction:

int years = year2 - year1;
int months = month2 - month1;
int days = day2 - day1;
String answer = Integer.toString(years) + "." + Integer.toString(months) + "." + Integer.toString(days);
Bobby
  • 1,416
  • 1
  • 17
  • 30