对任意输入的两个日期形字段如:(1872-07.01和2003-03-04)求他们之间相差多少年
并且要实现如下接口 
interface callback
{
void callback(data birthday,data deathday)
}

解决方案 »

  1.   

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.*;public class TestYear implements CallBack {
    private int START_YEAR = 1970;
    /**
     * @param args
     * @throws ParseException 
     */
    public static void main(String[] args) throws ParseException {
    // TODO Auto-generated method stub
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date birthday = sdf.parse("1872-07-01");
    Date deathday = sdf.parse("2003-03-04");
    new TestYear().callBack(birthday, deathday);
    } public void callBack(Date birthday, Date deathday) {
    // TODO Auto-generated method stub
    long livetime = deathday.getTime() - birthday.getTime();
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(livetime);
    int liveyears = cal.get(Calendar.YEAR) - START_YEAR;
    System.out.println("Live years : " + liveyears);
    }}interface CallBack
    {
    void callBack(Date birthday,Date deathday);
    }
      

  2.   

    import java.util.Date;
    interface callback {
      void callback(Data birthday,Data deathday);
    }import java.text.DateFormat;
    import java.util.Date;
    import java.util.GregorianCalendar;
    public class DateConvert interface callback {
      private int age;  public static String getDate(Date date) {
        GregorianCalendar dateTime = new GregorianCalendar();
        dateTime.setGregorianChange(date);
        Date d = dateTime.getTime();
        DateFormat df = DateFormat.getDateInstance();
        return df.format(d);
      }  public void callback(Data birthday,Data deathday) {
        String[] date2 = DateConvert.getDate(deathday).split("-");
        String[] date1 = DateConvert.getDate(birthday).split("-");
        int byear = Integer.parseInt(date1[0]);
        int bmonth = Integer.parseInt(date1[1]);
        int bday = Integer.parseInt(date1[2]);
        int nyear = Integer.parseInt(date2[0]);
        int nmonth = Integer.parseInt(date2[1]);
        int nday = Integer.parseInt(date2[2]);
        this.age = nyear - byear;
        if (bmonth > nmonth) {
          this.age = this.age - 1;
        }
        if (bmonth == nmonth) {
          if (bday > nday) {
            this.age = this.age - 1;
          }
        }
      }  public int getAge() {
        return this.age;
      }
    }