我正在学习如何构建Android应用程序,而我正试图从用户那里获得年龄,只使用生日。
我已经在使用Joda计时器,但我从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);
但是没有用。
谢谢。
答案 0 :(得分:1)
尝试使用以下方法计算用户年龄,并在参数中传递您从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;
}
答案 1 :(得分:1)
你刚刚错配了你的模式然后接受了一个使用分钟而不是几个月的答案(小" m"对比大" M)。 Joda-answer 将是(请注意不同的模式):
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());