年龄用户从日期选择器

时间:2016-05-26 12:25:39

标签: android datepicker

  • 我想计算年龄,用户从日期选择器中选择DOB
  • 日期选择器代码与所有地方相同

  • 我的约会格式:

    1990/06/07(获取此格式)

  • 我需要计算年龄,即当前日期 - DOB 2016-1990 = 26

代码:

public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar calendar = Calendar.getInstance();
            int yy = calendar.get(Calendar.YEAR);
            int mm = calendar.get(Calendar.MONTH);
            int dd = calendar.get(Calendar.DAY_OF_MONTH);

           int a = yy - calendar.get(Calendar.YEAR);
            Log.e("999999", String.valueOf(a));
            return new DatePickerDialog(getActivity(), this, yy, mm, dd);
        }
  • 它给了我0。那就是问题

1 个答案:

答案 0 :(得分:0)

您可以使用JodaTime库来获得有效的结果。

    String dateStr = "04/05/2010";

    SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
    Date dateObj = null;
    try {
        dateObj = curFormater.parse(dateStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }


    Period age = calcDiff(dateObj,new Date());
    Toast.makeText(this, PeriodFormat.wordBased().print(age),Toast.LENGTH_SHORT).show();

并使用此方法获得差异

  private Period calcDiff(Date startDate,Date endDate)
  {
    DateTime START_DT = (startDate==null)?null:new DateTime(startDate);
    DateTime END_DT = (endDate==null)?null:new DateTime(endDate);

    Period period = new Period(START_DT, END_DT);

    return period;

 }

或根据您的要求,您可以像这样更改PeriodFormat

 PeriodFormatter mPeriodFormat;
 mPeriodFormat = new PeriodFormatterBuilder().appendYears().appendSuffix(" year(s) ").appendMonths().appendSuffix(" month(s) ").appendDays().appendSuffix(" day(s) ").printZeroNever().toFormatter();
 Toast.makeText(this,mPeriodFormat.print(age),Toast.LENGTH_SHORT).show();