how to find the difference between datepicker in kotlin - android

Currently, I have a start date and a end date for my datepicker dialog. I am trying to find the difference in days between the start and the end date. And to make sure that the end date will not be is not on the earlier date
/* Calendar Start Date Button Click */
startdatepicker = findViewById(R.id.CalendarStartImage)
startdateview = findViewById(R.id.StartDateTextView)
val startCalendar = Calendar.getInstance()
val startPicker = DatePickerDialog.OnDateSetListener{ view, year, month,dayOfMonth ->
startCalendar.set(Calendar.YEAR,year)
startCalendar.set(Calendar.MONTH,month)
startCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth)
updateStartCalendar(startCalendar)
}
startdatepicker.setOnClickListener{
val dialog = DatePickerDialog(this,startPicker, startCalendar.get(Calendar.YEAR), startCalendar.get(Calendar.MONTH), startCalendar.get(Calendar.DAY_OF_MONTH))
// dialog.datePicker.minDate = startCalendar.getTimeInMillis()
dialog.datePicker.minDate = (System.currentTimeMillis()-1000)
dialog.show()
}
/* Calendar End Date Button Click */
enddatepicker = findViewById(R.id.CalendarEndImage)
enddateview = findViewById(R.id.EndDateTextView)
val endCalendar = Calendar.getInstance()
val endPicker = DatePickerDialog.OnDateSetListener{ view, year, month,dayOfMonth ->
endCalendar.set(Calendar.YEAR,year)
endCalendar.set(Calendar.MONTH,month)
endCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth)
// DatePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
updateEndCalendar(endCalendar)
}
enddatepicker.setOnClickListener{
val dialog = DatePickerDialog(this,
endPicker,
endCalendar.get(Calendar.YEAR),
endCalendar.get(Calendar.MONTH),
endCalendar.get(Calendar.DAY_OF_MONTH))
// dialog.datePicker.minDate = startCalendar.getTimeInMillis()
dialog.datePicker.minDate = (System.currentTimeMillis()-1000)
dialog.show()
}
}
private fun updateStartCalendar(startCalendar: Calendar){
val myformat = "MM-dd-yyyy"
val mydateformat = SimpleDateFormat(myformat,Locale.ENGLISH)
startdateview.text=(mydateformat.format(startCalendar.time))
}
private fun updateEndCalendar(endCalendar: Calendar){
val myformat = "MM-dd-yyyy"
val mydateformat = SimpleDateFormat(myformat,Locale.ENGLISH)
Log.d("check", endCalendar.time.toString())
enddateview.text=(mydateformat.format(endCalendar.time))
}

to check the time difference between two calendar dates you can use:
val duration = Duration.between(startCalendar, endCalendar)
val durationDays = duration.inWholeDays()
you can also check if it's negative using:
if(duration.isNegative){
//do something
} else{
//do something else
}

Related

How to get the days diffence between two date

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()
}

How to make End Date 1 day after the Start Day on android datePicker

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)
}

DatePicker dialog may showing improper date in kotlin

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())

How to get month from Material design Datepicker Android kotlin

I have a datepicker from material design, its opening well in the app.
Now how can i get for example the selected month from the datepicker.
Initialize the datepicker:
val datePicker = MaterialDatePicker.Builder.datePicker()
.setTitleText("Kies een datum")
.setSelection(MaterialDatePicker.todayInUtcMilliseconds())
.build()
On button hit the calendar opens:
fun pickDate() {
binding.DatepickerButton.setOnClickListener {
datePicker.show(activity?.supportFragmentManager!!, datePicker.toString())
}
}
so it shows, but i cannot get the data from it.
For Java 8, you can use Date/Time API
binding.DatepickerButton.addOnPositiveButtonClickListener {
var dateFormatter = DateTimeFormatter.ofPattern("MM", Locale.getDefault())
val month = dateFormatter.format(
Instant.ofEpochMilli(it)
.atZone(ZoneId.systemDefault()).toLocalDate()
)
}
Otherwise, you can use SimpleDateFormatter
binding.DatepickerButton.addOnPositiveButtonClickListener {
val calendar = Calendar.getInstance()
val simpleDateFormatter = SimpleDateFormat("MM", Locale.getDefault())
calendar.time = Date(it)
val month = simpleDateFormatter.format(calendar.time)
}
Try this click positive button click listener. after getting the date you can extract a month from it.
binding.DatepickerButton.addOnPositiveButtonClickListener {
val (startOfRange, endOfRange) = it // in case date range operation
val date = it // single select date
String dateString = DateFormat.format("dd/MM/yyyy", new Date(date)).toString();
}

android:kotlin:DatePickerDialog set minDate and maxDate

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
}

Categories

Resources