Android Joda-使用不同的格式从生日获取年龄

Android Joda-使用不同的格式从生日获取年龄,android,json,jodatime,Android,Json,Jodatime,我正在学习如何构建安卓应用程序,我试图从我的用户那里了解年龄,只使用生日 我已经在使用Joda timer,但是我从一个Json文件获取数据,这个Json文件输出如下数据: 1994-11-24 / YYYY-MM-d 在Java中,我在for循环中获取json数据 //Variable private static final String TAG_BIRTH_DATE = "birth_date"; ... //inside the Loop String birth_dat

我正在学习如何构建安卓应用程序,我试图从我的用户那里了解年龄,只使用生日

我已经在使用Joda timer,但是我从一个Json文件获取数据,这个Json文件输出如下数据:

1994-11-24 / YYYY-MM-d
在Java中,我在for循环中获取json数据

 //Variable

 private static final String TAG_BIRTH_DATE = "birth_date";
 ...

 //inside the Loop
 String birth_date = c.getString(TAG_BIRTH_DATE); 
我的问题是,我如何设置日期格式,并从此人处获取年龄

到目前为止,我试过这个

                DateTimeFormatter formatter = DateTimeFormat.forPattern("d/MM/yyyy");
                LocalDate date = formatter.parseLocalDate(birth_date);

                LocalDate birthdate = new LocalDate (date);
                LocalDate now = new LocalDate();
                Years age = Years.yearsBetween(birthdate, now);
但它不起作用


谢谢。

尝试下面的方法来计算用户年龄,并在参数中传递您从
JSON

public static int getAge(String dateOfBirth) {

    Calendar today = Calendar.getInstance();
    Calendar birthDate = Calendar.getInstance();

    int age = 0;

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
    Date convertedDate = new Date();
    try {
        convertedDate = dateFormat.parse(dateOfBirth);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    birthDate.setTime(convertedDate);
    if (birthDate.after(today)) {
        throw new IllegalArgumentException("Can't be born in the future");
    }

    age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);

    // If birth date is greater than todays date (after 2 days adjustment of
    // leap year) then decrement age one year
    if ((birthDate.get(Calendar.DAY_OF_YEAR)
            - today.get(Calendar.DAY_OF_YEAR) > 3)
            || (birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH))) {
        age--;

        // If birth date and todays date are of same month and birth day of
        // month is greater than todays day of month then decrement age
    } else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH))
            && (birthDate.get(Calendar.DAY_OF_MONTH) > today
                    .get(Calendar.DAY_OF_MONTH))) {
        age--;
    }

    return age;
}

您刚刚错配了您的模式,然后接受了一个使用分钟而不是月份的答案(小“m”与大“m”)。Joda的答案是(请注意不同的模式):


我错了,现在一切正常,谢谢你,伙计,你救了我的命。
String birth_date = c.getString(TAG_BIRTH_DATE); // example: 1994-11-24
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-d");
LocalDate date = formatter.parseLocalDate(birth_date);
Years age = Years.yearsBetween(date, LocalDate.now());