Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android How to change Total number of days into years,months and days exactly?

i am doing an app that is related to get the age of a person according to the given input of birthday date. for that i am getting the total number of days from that date to the current date from the below code.

      String strThatDay = "1991/05/10";
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
      Date d = null;
      try {

      try {
      d = formatter.parse(strThatDay);
      Log.i(TAG, "" +d);
      } catch (java.text.ParseException e) {

      e.printStackTrace();
      }
      } catch (ParseException e) {

      e.printStackTrace();
      } 
      Calendar thatDay = Calendar.getInstance();
      thatDay.setTime(d); //rest is the same....

      Calendar today = Calendar.getInstance();
      long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); 
      long days = diff / (24 * 60 * 60 * 1000);

from this code i am getting total number of days. so my requirement is convert the total number of days in to years ,months and days exactly.. please help....

like image 807
NagarjunaReddy Avatar asked Oct 05 '12 04:10

NagarjunaReddy


2 Answers

You should use the Duration class :

Duration duration = new Duration();
duration.add( today );
duration.substract( birthDate);
int years = duration.getYears();
int months = duration.getMonths();
int days = duration.getDays();

Some other alternatives include using a library dedicated to time management : Joda time. See Calculate age in Years, Months, Days, Hours, Minutes, and Seconds

like image 114
Snicolas Avatar answered Sep 27 '22 18:09

Snicolas


  String strThatDay = "1991/05/10";
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
  Date thatDate = null;
  try {

  try {
  thatDate = formatter.parse(strThatDay);

  Calendar thatDay = Calendar.getInstance();
  thatDay.setTime(thatDate);
  Calendar toDay = Calendar.getInstance();
  toDay.setTime(thatDate);

  toDay.add(Calendar.DATE, noOfDays);

  int year = toDay.getTime().getYear() - thatDay.getTime().getYear();
  int month  = toDay.getTime().getMonth() - thatDay.getTime().getMonth();
    if(month<0){
       year--
       month = month+12;
     }
  int days  = toDay.getTime().getDate() - thatDay.getTime().getDate();
     if(month<0){
       month--
       days = days+ toDay.getMaximum(Calendar.MONTH);;
     }
like image 44
Jignesh Ansodariya Avatar answered Sep 27 '22 18:09

Jignesh Ansodariya