how can set max date in date picker Kotlin android
how can set current date in max date so user cannot enter future date
val date =
OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
myCalendar.set(Calendar.YEAR, year)
myCalendar.set(Calendar.MONTH, monthOfYear)
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
dob.set(year,monthOfYear,dayOfMonth)
var age = today[Calendar.YEAR] - dob[Calendar.YEAR]
if (today[Calendar.DAY_OF_YEAR] < dob[Calendar.DAY_OF_YEAR]) {
age--
}
val ageInt = age
val ageS = ageInt.toString()
("Age : $ageS").also { binding.ageText.text = it }
updateLabel()
}
binding.edtBirthdate.setOnClickListener {
context?.let { it1 ->
DatePickerDialog(
it1, date, myCalendar[Calendar.YEAR],
myCalendar[Calendar.MONTH],
myCalendar[Calendar.DAY_OF_MONTH]
)
.show()
}
}
In Kotlin, you can do something like
DatePickerDialog(
it1, date, myCalendar[Calendar.YEAR],
myCalendar[Calendar.MONTH],
myCalendar[Calendar.DAY_OF_MONTH]
)
.apply { datePicker.maxDate = Date().time }
.show()
Related
How to calculate the days between two date for android studio in kotlin. There is two button for choosing date, after choosing the date, I want to compare two date and get the difference day between these two date.
Here is my code
tvDatePicker = findViewById(R.id.textViewDate)
btnDatePicker = findViewById(R.id.btn_datePicker)
EndDatePicker = findViewById(R.id.textViewBookEnd)
btnEndDatePicker = findViewById(R.id.btn_EndDatePicker)
val myCalendar = Calendar.getInstance()
val datePicker = DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
myCalendar.set(Calendar.YEAR,year)
myCalendar.set(Calendar.MONTH,month)
myCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth)
updateStartDate(myCalendar)
}
val endDatePicker = DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
myCalendar.set(Calendar.YEAR,year)
myCalendar.set(Calendar.MONTH,month)
myCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth)
updateEndDate(myEndCalendar)
}
btnDatePicker.setOnClickListener{
DatePickerDialog(this,datePicker, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show()
}
btnEndDatePicker.setOnClickListener{
DatePickerDialog(this,endDatePicker, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show()
}
private fun updateStartDate(myCalendar: Calendar){
val myFormat = "dd-MM-yyyy"
val sdf = SimpleDateFormat(myFormat, Locale.UK)
tvDatePicker.setText(sdf.format(myCalendar.time))
}
private fun updateEndDate(myCalendar: Calendar){
val myFormat = "dd-MM-yyyy"
val sdf = SimpleDateFormat(myFormat, Locale.UK)
EndDatePicker.setText(sdf.format(myCalendar.time))
}
private fun dayDifference(startCalendar: Calendar, endCalendar: Calendar): Long {
val diff = endCalendar.timeInMillis - startCalendar.timeInMillis
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS).toInt()
}
Below is the date picker dialog in one of the fragment and I am getting the error shown below
Type mismatch: inferred type is Int but LocalDate was expected
on line:
viewModel.onDateSelected(year, month, dayOfMonth)
private val datePickerDialog by lazy {
DatePickerDialog(requireActivity(), R.style.DatePicker).apply {
setTitle(R.string.select_date)
datePicker.maxDate = LocalDate.now().minusDays(0).toMillis()
setOnDateSetListener { _, year, month, dayOfMonth ->
viewModel.onDateSelected(year, month, dayOfMonth)
}
}
}
As unowsp pointed out, seems that you need a localDate.
Try something like:
setOnDateSetListener { _, year, month, dayOfMonth ->
val calendar = Calendar.getInstance()
calendar.set(Calendar.YEAR, year)
calendar.set(Calendar.MONTH, month)
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
val localDate = LocalDateTime.ofInstant(calendar.toInstant(), calendar.timeZone.toZoneId())
.toLocalDate()
viewModel.onDateSelected(localDate)
}
i have a project that should bring end date after the start date on android datepicker.
(user will chose any date on start date and when user click end date what ever user choose end date should be one day after start date)
for this purpose i have a Kotlin code as in below;
private fun showDatePickerDialog(type: Int) {
calendar = Calendar.getInstance()
year = calendar!!.get(Calendar.YEAR)
month = calendar!!.get(Calendar.MONTH)
dayOfMonth = calendar!!.get(Calendar.DAY_OF_MONTH)
datePickerDialog = DatePickerDialog(
requireContext(), R.style.MyDatePickerStyle,
{ datePicker, year, month, day ->
if (type == 0){
var month = month + 1
var startMonthConverted = ""+month
var startDayConverted = ""+day
if(month<10){
startMonthConverted = "0$startMonthConverted"
}
if(day<10){
startDayConverted= "0$startDayConverted"
}
binding.txtStartDate.setText("$year-$startMonthConverted-$startDayConverted")
} else {
var month = month + 1
var monthConverted = ""+month
var dayConverted = ""+day
if(month<10){
monthConverted = "0$monthConverted";
}
if(day<10){
dayConverted = "0$dayConverted"
}
binding.txtEndDate.setText("$year-$monthConverted-$dayConverted")
}
},
year,
month,
dayOfMonth
)
if (type == 0) {
val startDay = Calendar.getInstance()
startDay.add(Calendar.DAY_OF_YEAR, 2);
datePickerDialog!!.datePicker.minDate = startDay.timeInMillis
} else {
val endDay = Calendar.getInstance()
endDay.add(Calendar.DATE, 2)
// datePickerDialog!!.datePicker.minDate = endDay.timeInMillis
datePickerDialog!!.getDatePicker().setMinDate(endDay.getTimeInMillis());
}
val df: DateFormat = SimpleDateFormat("'T'HH:mm:ss.SSS")
currentTime = df.format(Calendar.getInstance().timeInMillis)
Log.d("TAG", "currentTime:$currentTime ")
datePickerDialog!!.show()
//set OK/Cancel buttons color
//set OK/Cancel buttons color
datePickerDialog!!.getButton(Dialog.BUTTON_POSITIVE)
.setTextColor(android.graphics.Color.BLACK)
datePickerDialog!!.getButton(Dialog.BUTTON_NEGATIVE)
.setTextColor(android.graphics.Color.BLACK)
}
Below is the function I am using to diplay date picker dialog in android.
private fun openPurchaseDatePickerDialog(
yearToDisplay: Int,
monthToDisplay: Int,
dayToDisplay: Int
) {
try {
activity?.let { KeyboardUtils.hideKeyboard(it) }
val calendar = Calendar.getInstance()
val dialog = DatePickerDialog(activity, { _, year, month, day_of_month ->
calendar[Calendar.YEAR] = year
calendar[Calendar.MONTH] = month
calendar[Calendar.DAY_OF_MONTH] = day_of_month
val myFormat = "" + DateUtils.OverAllAppDateDisplayFormat
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
edtPurchaseDate.setText(sdf.format(calendar.time).toString())
spIntendedUse.isFocusable = true
}, yearToDisplay, monthToDisplay, dayToDisplay)
dialog.updateDate(yearToDisplay,monthToDisplay,dayToDisplay)
dialog.datePicker.maxDate = calendar.timeInMillis
dialog.show()
} catch (e: Exception) {
e.printStackTrace()
}
As above you can check that there are three arguments passed in this function.
I have to show the specific date in DatePicker dialog show I have passed this three parameters.
Means If User selected the date first time the default values will be set or the current date will be set.
If edittext has already a text selected and not empty am doing as below :
if (edtPurchaseDate.text.toString().isNullOrEmpty()) {
val calendar = Calendar.getInstance()
openPurchaseDatePickerDialog(
calendar[Calendar.YEAR],
calendar[Calendar.MONTH],
calendar[Calendar.DAY_OF_MONTH]
)
} else {
var dateArr = edtPurchaseDate.text.toString().split("-")
openPurchaseDatePickerDialog(
dateArr[2].toInt(),
dateArr[1].toInt(),
dateArr[0].toInt()
)
}
But Still when the date picker dialogs opens its displaying the selected as as today instead of custom.
What might be the issue?
You can see I have also tried with updateDate() function as below :
dialog.updateDate(yearToDisplay,monthToDisplay,dayToDisplay)
Thanks.
Not completely sure about the updateDate method issue here . But to fix this you can use same Calendar object during initialization it should work fine .
i have modified your method a bit .
private fun openPurchaseDatePickerDialog(date: String) {
try {
val calendar = Calendar.getInstance()
if (date.isNotBlank()) {
try {
calendar.time = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).parse(date)!!
}catch (e:ParseException){
}
}
val dialog = DatePickerDialog(this, { _, year, month, day_of_month ->
calendar[Calendar.YEAR] = year
calendar[Calendar.MONTH] = month
calendar[Calendar.DAY_OF_MONTH] = day_of_month
val myFormat = "dd-MM-yyyy"
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
edtPurchaseDate.setText(sdf.format(calendar.time).toString())
}, calendar[Calendar.YEAR], calendar[Calendar.MONTH], calendar[Calendar.DAY_OF_MONTH])
dialog.datePicker.maxDate = System.currentTimeMillis()
dialog.show()
} catch (e: Exception) {
e.printStackTrace()
}
}
Now when you call it you just call it with a value you do mnot have to split String.
openPurchaseDatePickerDialog(edtPurchaseDate.text.toString())
I'm trying to set a datepicker where the user will choose a date and if it's under 18 years old and if not it will show a message.
Until now I have that the date picker can't choose future dates, but I don't know how to make the condition to ckeck if the user's date has under 18 years. Any help would be appreciated.
fun setupBirthdateDatePicker() {
val c: Calendar = Calendar.getInstance()
val year: Int = c.get(Calendar.YEAR)
val month: Int = c.get(Calendar.MONTH)
val day: Int = c.get(Calendar.DAY_OF_MONTH)
setClickListener {
val dialog = if (textInput.text.isNullOrEmpty()) {
DatePickerDialog(context,
{ view, year, month, dayOfMonth ->
textInput.setText(Utils.getDateFromDatePicker(year, month, dayOfMonth))
}, year, month, day)
} else {
DatePickerDialog(context,
{ view, year, month, dayOfMonth ->
textInput.setText(Utils.getDateFromDatePicker(year, month, dayOfMonth))
},
Utils.getYearFromDate(textInput.text.toString()),
Utils.getMonthFromDate(textInput.text.toString()),
Utils.getDayFromDate(textInput.text.toString()))
}
dialog.datePicker.maxDate = c.timeInMillis
dialog.show()
}
}
If you want 18 years ago in epoch milliseconds to set as the max/starting date of your picker, you can use:
(ZonedDateTime.now() - Period.ofYears(18)).toInstant().toEpochMilli()
Or if you want to validate, you can compare like this:
val eighteenYearsAgo = LocalDate.now() - Period.ofYears(18)
val listener = DatePickerDialog.OnDateSetListener { _, year, month, day ->
// +1 month because DatePicker's month is unfortunately zero-based
val pickedDate = LocalDate.of(year, month + 1, day)
if (pickedDate < eighteenYearsAgo) {
// Picked a date less than 18 years ago
}
}