How to get the days diffence between two date - android

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

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

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

how to find the difference between datepicker in kotlin

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
}

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 can set max date in date picker kotlin android

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

Categories

Resources