Android如何更改几年,几个月和几天的总天数?

时间:2012-10-05 04:22:13

标签: android calendar date-format

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

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

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

2 个答案:

答案 0 :(得分: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时间。见Calculate age in Years, Months, Days, Hours, Minutes, and Seconds

答案 1 :(得分: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);;
     }