Android How to change Total number of days into ye

2019-06-21 17:49发布

问题:

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....

回答1:

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



回答2:

  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);;
     }