5

我正在做一个与根据生日日期的给定输入获取一个人的年龄相关的应用程序。为此,我从下面的代码中获取了从该日期到当前日期的总天数。

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

从这段代码中,我得到了总天数。所以我的要求是将总天数准确地转换为年、月和日..请帮助....

4

2 回答 2

6

你应该使用这个Duration类:

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

其他一些替代方法包括使用专门用于时间管理的库:Joda time。请参阅以年、月、日、小时、分钟和秒为单位计算年龄

于 2012-10-05T04:34:15.367 回答
3
  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);;
     }
于 2012-10-05T04:56:55.357 回答