生年月日(dob)が与えられた場合、アンドロイドで現在の年齢を計算する方法:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
textView_cage = (TextView) findViewById(R.id.textView_cage);
textView_currentagediff = (TextView) findViewById(R.id.textView_currentagediff);
textView4 = (TextView) findViewById(R.id.textView4);
mPickDate = (Button) findViewById(R.id.pickDate);
mPickDate.setOnClickListener(new View.OnClickListener() {
@SuppressLint("ValidFragment")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
});
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println("Current Setdate");
System.out.println("Year" + year);
System.out.println("Month" + month);
System.out.println("Date" + day);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
mDateDisplay.setText(String.valueOf(day) + "/" + String.valueOf(month + 1) + "/" + String.valueOf(year));
Date d = new Date(year, month, day);
System.out.println("Current Setdate");
Date d1 = new Date();
int year2 = d1.getYear();
int month2 = d1.getMonth();
int day2 = d1.getDate();
System.out.println("Current aaj ki date");
System.out.println("Year" + year2);
System.out.println("Month" + month2);
System.out.println("Date" + day2);
int year3 = year2 - year;
int month3 = (month2 + 1) - month;
int day3 = day2 - day;
System.out.println("Current aaj kitnhesal k ho gaye ");
System.out.println("Year" + year3);
System.out.println("Month" + month3);
System.out.println("Date" + day3);
setnewage(year3, month3, day3);
}
private void setnewage(int year4, int month4, int day4) {
Date d5 = new Date(year4, month4, day4);
CharSequence day = DateFormat.format("d", d5);
CharSequence month = DateFormat.format("M", d5);
CharSequence year = DateFormat.format("yyyy", d5);
textView_currentagediff.setText(year + " Years " + month + " Months and " + day + " days");
Date d1 = new Date();
int year2 = d1.getYear();
int month2 = d1.getMonth();
int day2 = d1.getDate();
}
}
}
生年月日を選択したいのですが、日付Datepickerdialog
選択後、現在の年齢を取得したいです。Androidでの例を教えてください。