首页 > 解决方案 > 如何将原始日期字符串转换为年龄?

问题描述

我有一个表格用于输入数据和我的生日,顺便说一下我使用 volley 所以在我的代码中我使用jsonResponse. 我没有使用诸如DatePickeror之类的东西CalendarView。我只是将输入类型设置为“日期”。所以我将它转换为字符串,它的格式为MM/dd/yyyy.

如何将字符串日期转换为年龄?

有人可以帮我解决一个功能吗?

这是我的代码。

String strBirthDate = "BirthDate: " + object.getString("birth_date").trim();

birthDate.setText(strBirthDate);

字符串会像1/1/1990

有什么办法可以将这些部分划分并转换为年龄?

标签: android

解决方案


试试这个代码 -

    String currentString =strBirthDate;//  "01/01/1990";
    String[] separated = currentString.split("/");
    String month = separated[0]; // this will contain "01"

    String[] YearMonth = separated[1].currentString.split("/"); // this will contain " 01/1990"

    String day = YearMonth[0];// this will contain " 01/1990"
    String year = YearMonth[1];// this will contain " 1990"

    int year1 = Integer.parseInt(year);
    int month1 = Integer.parseInt(month);
    int day1 = Integer.parseInt(day);
    birthDate.setText(getAge(year1,month1,day1));       


private String getAge(int year, int month, int day){
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();

dob.set(year, month, day); 

int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
    age--; 
}

Integer ageInt = new Integer(age);
String ageS = ageInt.toString();

return ageS;  
}

推荐阅读