android - 如何将原始日期字符串转换为年龄?
问题描述
我有一个表格用于输入数据和我的生日,顺便说一下我使用 volley 所以在我的代码中我使用jsonResponse
. 我没有使用诸如DatePicker
or之类的东西CalendarView
。我只是将输入类型设置为“日期”。所以我将它转换为字符串,它的格式为MM/dd/yyyy
.
如何将字符串日期转换为年龄?
有人可以帮我解决一个功能吗?
这是我的代码。
String strBirthDate = "BirthDate: " + object.getString("birth_date").trim();
birthDate.setText(strBirthDate);
字符串会像1/1/1990
有什么办法可以将这些部分划分并转换为年龄?
解决方案
试试这个代码 -
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;
}
推荐阅读
- python-3.x - 通过python中的函数对列表进行排序
- ruby-on-rails - 如何访问 update_all 生成的原始 SQL 语句(ActiveRecord 方法)
- bigdata - 使用 Nifi 表达语言处理多个状态变化
- python - 从浏览器下载文件时选择另存为按钮
- mysql - 每行的动态数据透视表(MySql)
- c# - Bot Framework 在活动事件的内存存储中使用
- javascript - 为 no-undef 设置忽略列表(定义来自其他来源的预期变量)
- xamarin - 具有本地内容的 Xamarin.Forms WebView 未触发导航事件
- php - example.com/wp-login.php 将我重定向到 example.com/example.com/wp-admin
- python - 将输入读入嵌套列表