How do I calculate age from my date picker? - android

I am learning Kotlin on my own. I am trying to calculate the age of a user after the have input their date of Birth and display it in another activity.
I tried a bunch of different stuff and none worked. I'm sure I maybe overlooking something simple.
my code:
class MainActivity : AppCompatActivity() {
var date1: EditText? = null
var datePickerDialog: DatePickerDialog? = null
lateinit var submitButton: Button
lateinit var userInput: EditText
lateinit var dob: EditText
#SuppressLint("SetTextI18n", "MissingInflatedId", "CutPasteId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layout.activity_main)
date1 = findViewById<EditText>(id.date) as EditTe
date1!!.setOnClickListener{ // calender class's instance and get current date , month and year from calender
val c = Calendar.getInstance()
val mYear = c[Calendar.YEAR] // current year
val mMonth = c[Calendar.MONTH] // current month
val mDay = c[Calendar.DAY_OF_MONTH] // current day
datePickerDialog = DatePickerDialog(
this#MainActivity,
{ view, year, monthOfYear, dayOfMonth -> // set day of month , month and year value in the edit text
date1!!.setText(
dayOfMonth.toString() + "/"
+ (monthOfYear + 1) + "/" + year
)
}, mYear, mMonth, mDay
)
datePickerDialog!!.show()
}
submitButton = findViewById(id.sub_btn)
userInput = findViewById(id.username1)
dob = findViewById(id.date)
submitButton.setOnClickListener {
val age= dob.text.toString()
val name= userInput.text.toString()
//val str = userInput.text.toString()
intent = Intent(this, CardReturn::class.java)
intent.putExtra("message_key","Name:$name")
intent.putExtra("message_key1","DOB:$age")
startActivity(intent)
}
}}

If you're able to utilize java.time or at least ThreeTen Android Backport, it should be easy and will save you from a lot of work if your'e using java.util.Calendar.
Here's a small working piece of DatePickerDialog that you can copy and paste easily, this is how I calculate year difference between two LocalDate instance
val now = LocalDateTime.now()
val initYear = now.year
val initMonth = now.monthValue - 1 // offset it -1 because January starts at 0 index
val initDay = now.dayOfMonth
val datePickerDialog = DatePickerDialog(
this#ActivityOrContext,
{ _: DatePicker, pickedYear: Int, pickedMonth: Int, pickedDay: Int ->
val selectedBirthdate = LocalDate.of(pickedYear, pickedMonth + 1, pickedDay)
val age = Period.between(selectedBirthdate, LocalDate.now()).years
Log.e("DatePickerTag", "Age : $age")
}, initYear, initMonth, initDay)
If I select April 1 1995 and evaluate it against the time of this posting it will print
E/DatePickerTag: Age : 27
If however you can't use java.time or ThreeTenABP, this S.O post might help you otherwise. The bottom section of the post contains answers for calculating age using java.util.Calendar.
Lastly, out-of-topic, consider what lateinit var is for, what kotlin null safety is, and avoid shouting in your code unnecessarily!!

Inside layout file
<DatePicker
android:id="#+id/ageSelectionPicker"
style="#style/MyDatePicker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginTop="16dp"
android:layout_marginRight="24dp"
android:backgroundTint="#ff4081"
android:calendarTextColor="#ff4081"
android:calendarViewShown="false"
android:datePickerMode="spinner" />
class.java
DatePicker ageSelectionPicker = findViewById(R.id.ageSelectionPicker);
int age = getAge(ageSelectionPicker.getYear(), ageSelectionPicker.getMonth(), ageSelectionPicker.getDayOfMonth());
Method getAge
private int getAge(int year, int month, int day) {
Calendar dateOfBirth = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dateOfBirth.set(year, month, day);
int age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dateOfBirth.get(Calendar.DAY_OF_YEAR)) {
age--;
}
return age;
}

Related

How to Store an YEAR from DatePickerDialog in Kotlin?

So basically i want to get the year from the user using the datePickerDialog and then substract that year to the current year. Till this i have no issues.
The problem is i have button created and want users to get a Toast message if they haven't chosen the date. I am using if else and validating the Year when the datePicker is not selected.
Also the year i am getting after the datePickerDialog is the current year.
Here is the Code -
fun birthdayPicker() {
val cal = Calendar.getInstance()
val year = cal.get(Calendar.YEAR)
val month = cal.get(Calendar.MONTH)
val date = cal.get(Calendar.DATE)
val textcheck : TextView = findViewById(R.id.yourage)
val dateSelected = findViewById<TextView>(R.id.text_view_date_1)
dateSelected.setOnClickListener {
val datePickerDialog = DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener { _, myear, mmonth, mdayOfMonth ->
dateSelected.setText("" + mdayOfMonth + "/" + mmonth + "/" + myear)
// Toast.makeText(this, "$myear", Toast.LENGTH_SHORT).show()
},
year,
month + 1,
date
)
datePickerDialog.show()
}
val button = findViewById<Button>(R.id.button_date_1)
button.setOnClickListener {
val selectedyear : Int = year
if (selectedyear.toString().isBlank()) {
Log.e("Main","$selectedyear")
Toast.makeText(this, "Choose an Year", Toast.LENGTH_SHORT).show()
}
else {
val checkingYear = Calendar.getInstance().get(Calendar.YEAR)
textcheck.text = (checkingYear - selectedyear).toString()
}
}
}
so you just store that into a variable as so
val myFormat = "MM/dd/yyyy" //mention the format you need
val sdf = SimpleDateFormat(myFormat, Locale.US)
val currentDate = sdf.format(cal.getTime())

How can I add months Int to a choosen date on date picker in android Kotlin?

I have a working date picker in my app that replaces an EditText after a date selection. I want to add duration through a RadioGroup button that prints an Int to provoke an end date. How can I do that? I've spent the last two days without getting the result I'm looking to get.
Here is what I've got so far.
val datePicker = findViewById<DatePicker>(R.id.date_Picker)
val today = Calendar.getInstance()
datePicker.init(
today.get(Calendar.YEAR),
today.get(Calendar.MONTH),
today.get(Calendar.DAY_OF_MONTH
) { view, year, month, day ->
val month = month + 1
val startDay = ("$day-$month-$year")
binding.fechadeinicio.text = fechainicio
val duration = when (binding.duracion.checkedRadioButtonId) {
R.id.doce -> 12
R.id.veinticuatro -> 24
R.id.treintayseis -> 36
else -> 36
}
// val endDate = startDate.plusMonths(Duration.toLong())
// binding.endDate.text = endDate.toString()
}
Here is the closest one to the result I'm looking to get. Yet, I want to use the selected date val startDay, instead of val date = LocalDate.parse("2020-05-03"). When I replace it, the app crashes.
val date = LocalDate.parse("2020-05-03")
// Displaying date
println("Date : $date")
// Add 2 months to the date
val newDate = date.plusMonths(2)
println("New Date : $newDate")
Please, let me know how I can get the desired result?
Thanks.
I want to use the selected date that is val startDay instead of val date = LocalDate.parse("2020-05-03"). When I replace it, the app crashes.
val startDay = ("$day-$month-$year") here you've created date as dd-MM-yyyy, but by default LocalDate.parse uses DateTimeFormatter.ISO_LOCAL_DATE to parse a string, that parses a string of format yyyy-MM-dd to LocalDate. That's why it's crashing as your date is invalid according to that format.
You have to provide a DateTimeFormatter of pattern dd-MM-yyyy to parse your date.
You can do it like this
val startDay = ("$day-$month-$year")
val dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
binding.fechadeinicio.text = fechainicio
val duration = when (binding.duracion.checkedRadioButtonId) {
R.id.doce -> 12
R.id.veinticuatro -> 24
R.id.treintayseis -> 36
else -> 36
}
val startDate = LocalDate.parse(startDay, dateFormatter)
val endDate = startDate.plusMonths(duration.toLong()).format(dateFormatter)
binding.endDate.text = endDate
DatePicker returns year, month and day int values, now on creating date like val startDay = ("$day-$month-$year") would result in single digit for days and months less than 10, which would return 1 Jan 2020 as 1-1-2020 but date formatter is expecting it to be 01-01-2020.
To deal with this, we've to format int values before assigning it to the startDay, we can use format method of String to return 2 digits like this "%02d".format(intValue)
Change
val startDay = ("$day-$month-$year")
to
val startDay = "${"%02d".format(day)}-${"%02d".format(month)}-$year"
You can use LocalDate using of function.
Example here:
val date = LocalDate.of(year, month, day)
// Displaying date
println("Date : $date")
// Add 2 months to the date
val newDate = date.plusMonths(2)
println("New Date : $newDate")

Set date and get Date from Material Date Picker in Kotlin Android

I'm learning kotlin and at the moment I don't know much, I want to change a datepicker that I have for one of type Material, the problem is that I don't know how to pass the data to this new date picker.
This is the one I have at the moment:
fecha = view.findViewById(R.id.fecha)
fecha?.setOnClickListener {
fecha!!.error = null
val dateSetListener = DatePickerDialog(requireContext(), { _, year, monthOfYear, dayOfMonth ->
cal.set(Calendar.YEAR, year)
mYear = year
cal.set(Calendar.MONTH, monthOfYear)
mMonth = monthOfYear
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
mDay = dayOfMonth
updateDateInView()
}, mYear, mMonth, mDay)
dateSetListener.datePicker.maxDate = System.currentTimeMillis()
dateSetListener.show()
}
fun updateDateInView() {
val myFormat = "dd/MM/yyyy"
val sdf = SimpleDateFormat(myFormat)
fecha?.setText(sdf.format(cal.time))
}
I want to make it like this but I don't know how to pass and save the values, could someone help me?
val datePicker = MaterialDatePicker.Builder.datePicker().build()
MaterialDatePicker accepts CalendarConstraints to open the date picker on a certain month. CalendarConstraints accepts timeInMilliseconds to open calendar on a particular month. MaterialDatePicker has an addOnPositiveButtonClickListener method whose lambda returns the time in milliseconds after the user makes a selection.
You can create MaterialDatePicker like this
val myFormat = "dd/MM/yyyy"
val formattedDate = "01/01/2000"
val sdf = SimpleDateFormat(myFormat)
val date = sdf.parse(formattedDate)
val timeInMillis = date.time
val constraintBuilder = CalendarConstraints.Builder().setOpenAt(
timeInMillis //pass time in milli seconds
).build()
val picker = MaterialDatePicker.Builder.datePicker()
.setTitleText("Select Date")
.setCalendarConstraints(constraintBuilder)
.build()
picker.addOnPositiveButtonClickListener {
val date = Date(it)
val formattedDate = sdf.format(date) // date selected by the user
}
// show picker using this
picker.show(requireActivity().supportFragmentManager, "materialDatePicker")
Instead of using SimpleDateFormatter, you should use LocalDateTime API provided in Java8
Using LocalDateTime API, you can do the same like this
val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.getDefault())
val formattedDate = "01/01/2000"
val timeInMillis = LocalDate.parse(formattedDate, dateFormatter)
.atStartOfDay(ZoneId.systemDefault())
.toInstant()
.toEpochMilli()
You can pass this timeInMillis to setOpenAt() method of CalendarConstraintSet.
To get the date after the user makes a selection
val timeInMillis = dateFormatter.format(
// it is the milliseconds received inside lambda of addOnPositiveButtonClickListener
Instant.ofEpochMilli(it)
.atZone(ZoneId.systemDefault()).toLocalDate()
)

My app is closing after i pic the date , can anyone help me , i have attatched the code

This is my code and it crashes after i select the date in date picker dialog
bdaybutton.setOnClickListener { view -\\\>
val c = Calendar.getInstance()
val cyear = c.get(Calendar.YEAR)
val cmonth = c.get(Calendar.MONTH)
val cday = c.get(Calendar.DAY_OF_MONTH)
val abc = DatePickerDialog( this , DatePickerDialog.OnDateSetListener
{ view , year, month, day -\\\>
flag2 = true
year2 = year
val selecteddate = "${day/month+1/year}"
bdaydatetext.text = "${day/month+1/year}"
val sdf = java.text.SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH)
val date2 = sdf.parse(selecteddate)
time2 = date2.time.toInt()
}, cyear, cmonth, cday)
abc.show()
]
}
The error in the imge appears when after selecting the date
"${day/month+1/year}"
This computes the expression inside the {} and converts it to a string. Looks like you wanted something like
"${day}/${month+1}/${year}"
instead there.
Better yet, skip the string conversion step altogether and use something like Java 8 LocalDate or LocalDateTime directly instead.

How to disable future date and today date for date of birth in android kotlin

calendar.setOnClickListener {
datePicker = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view: DatePicker?, year: Int, month: Int, dayOfMonth: Int ->
val curDate = String.format("%d-%02d-%02d", year , (month+1), dayOfMonth)
date_text.setText(curDate)
}, year, month, day)
datePicker!!.datePicker.maxDate = (System.currentTimeMillis() - 1000)
datePicker!!.show()
}
How to select the dob must be a date before today. Please help me to do this
Use it this way :
val calender = getInstance()
calender[HOUR_OF_DAY] = 0
calender[MINUTE] = 0
calender[SECOND] = 0
Then use this in your code
datePicker!!.datePicker.maxDate = calendar.timeInMillis
This way the max date will be set to midnight of today's date.

Categories

Resources