I am using DatePickerDialog in my Android project using Kotlin. I have successfully created DatePickerDialog and its working fine.
Now I want to give some validation like in DatePickerDialog I want to disable future date.
For Example, Today date is 22 Aug 2019 I want to disable all date after today date.
I tried to use dateSetListener.getDatePicker().setMaxDate(System.currentTimeMillis())
but it's not working
var cal = Calendar.getInstance()
// create an OnDateSetListener
val dateSetListener = object : DatePickerDialog.OnDateSetListener {
override fun onDateSet(
view: DatePicker, year: Int, monthOfYear: Int,
dayOfMonth: Int
) {
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, monthOfYear)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
updateDateInView()
}
// dateSetListener.getDatePicker().setMaxDate(calendar.getTimeInMillis());
}
// when you click on the button, show DatePickerDialog that is set with OnDateSetListener
button_date!!.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
DatePickerDialog(this#MainActivity,
dateSetListener,
// set DatePickerDialog to point to today's date when it loads up
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)).show()
}
})```
Try this
var dialog = DatePickerDialog(
this#MainActivity,dateSetListener,
// set DatePickerDialog to point to today's date when it loads up
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
)
dialog.datePicker.maxDate = Calendar.getInstance().timeInMillis
dialog.show()
Related
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()
)
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.
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
}
}
I tried so many Codes but failed Is there is any library or can we do this with an android studio built-in date picker?
This is my last tried code
Calendar today = Calendar.getInstance();
Calendar twoDaysAgo = (Calendar) today.clone();
twoDaysAgo.add(Calendar.DATE, -2);
Calendar twoDaysLater = (Calendar) today.clone();
twoDaysLater.add(Calendar.DATE, 2);
datePicker.setMinDate(twoDaysAgo.getTimeInMillis());
datePicker.setMaxDate(twoDaysLater.getTimeInMillis());
Android DatePicker doesn't support that built-in. You can either create your own custom DatePicker. Or use 3rd party library like MaterialDateTimePicker
which allows you to also set setMinDate, setMaxDate, and setDisabledDays combined to achieve what you want, or even you can use setSelectableDays and providing calendar for prior the 7 days and another for post the 7 days.
You can disable past days in Date picker. Please refer below code snippets.
DatePickerDialog datePickerDialog = new DatePickerDialog(
getActivity(),
(datePicker, year, month, day) -> {
},
dateCal.get(Calendar.YEAR), dateCal.get(Calendar.MONTH), dateCal.get(Calendar.DAY_OF_MONTH));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 7);
datePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());
datePickerDialog.getDatePicker().setCalendarViewShown(false);
datePickerDialog.show();
Yes, there is a way to disable next 7 days in Material Date Picker. To use material date picker just add gradle dependency: implementation 'com.google.android.material:material:1.3.0'
In Java
private void showNext7DaysDisableDatePicker(){
Calendar today = Calendar.getInstance();
Calendar next7Days = Calendar.getInstance();
next7Days.add(Calendar.DAY_OF_YEAR, 7);
CalendarConstraints calendarConstraints = new CalendarConstraints.Builder()
.setValidator(new CalendarConstraints.DateValidator() {
#Override
public boolean isValid(long date) {
return date <= today.getTimeInMillis() || date >= next7Days.getTimeInMillis();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
}
})
.build();
MaterialDatePicker.Builder.datePicker()
.setCalendarConstraints(calendarConstraints)
.build()
.show(getSupportFragmentManager(),"MATERIAL_DATE_PICKER");
}
In Kotlin
private fun showNext7DaysDisableDataPicker() {
val today = Calendar.getInstance()
val next7Days = Calendar.getInstance()
next7Days.add(Calendar.DAY_OF_YEAR, 7)
val constraint = CalendarConstraints.Builder()
.setValidator(object : CalendarConstraints.DateValidator {
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(p0: Parcel?, p1: Int) {
}
override fun isValid(date: Long): Boolean {
if (date > today.timeInMillis && date < next7Days.timeInMillis) return false
return true
}
}).build()
val materialDatePicker = MaterialDatePicker.Builder.datePicker()
.setCalendarConstraints(constraint)
.build()
materialDatePicker.show(supportFragmentManager, "MATERIAL_DATE_PICKER")
}
I want set minData and maxDate
val dpd = DatePickerDialog(this,
DatePickerDialog.OnDateSetListener {
view, year, month, dayOfMonth ->
Log.d("DatePickerDialog","$year-$month+1-$dayOfMonth")
mDate[0]=year
mDate[1]=month+1
mDate[2]=dayOfMonth
}, mDate[0],mDate[1]-1,mDate[2])
val tmpmonth=afterDate[1]-1
val sdf = SimpleDateFormat("$afterDate[0]-$tmpmonth-$afterDate[2]")
val df = SimpleDateFormat("yyyy.MM.dd HH:mm")
val hee:Long=df.parse(datestr).time
dpd.datePicker.maxDate(hee) //<-----error
dpd.show()
there is an error "maxDate is the type of Long can't be invoked as function, the function invoke() is not found"
// If I have value like this
//val year:Int=2019
//val month:Int=10
//val day:Int=14
//I want to change to Long
fun convert_YearMonthDay_to_Long(year:Int, month:Int, year:Int):Long{
//how?????
}
change this line of code dpd.datePicker.maxDate(hee) to dpd.datePicker.setMaxDate(hee) or dpd.datePicker.maxDate = hee , it will work, dpd.datePicker.maxDate used to return the maxDate in long which is set to datepicker you want to set the date not to get it and this method need long value only and you are passing long value only
You can use Long.toInt(), but it is not safe, you can use this:
fun Long.toIntOrNull(): Int? {
val i = this.toInt()
return if (i.toLong() == this) i else null
}