我有一个用于输入数据的表格,在我生日的时候,我使用的是凌空抽空,所以在我的代码中,我使用的是jsonResponse
。我没有使用诸如DatePicker
或CalendarView
之类的东西。我只是将输入类型设置为“日期”。因此,我将其转换为字符串,其格式为MM/dd/yyyy
。
如何将字符串日期转换为年龄?
有人可以帮我一个功能吗?
这是我的代码。
String strBirthDate = "BirthDate: " + object.getString("birth_date").trim();
birthDate.setText(strBirthDate);
字符串将像1/1/1990
有什么方法可以将这些部分划分为年龄吗?
答案 0 :(得分:1)
尝试此代码-
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;
}
答案 1 :(得分:1)
只需将日期字符串传递给此方法。如果您的日期为29
,这将使您返回1/1/1990
之类的年龄。
尝试一下:
public String getAge(String dateString){
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date readDate = null;
try {
readDate = df.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(readDate.getTime());
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
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;
}