Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a date from a DatePickerDialog in Kotlin Android

Tags:

android

kotlin

The below snippet of code 'works' in the sense it updates the statusDateID correctly. the issue I am having is that although it sets the statusDateID correctly, the date will not persist, and when I update mh.entryDate it is always the current date.

How do I get the date outside of the dialog. so that I can update mh.entryDate with the chosen date, not the current date.

Thank you for your time.

fun changeDate(view: View) {

    var date: Calendar = Calendar.getInstance()
    var thisAYear = date.get(Calendar.YEAR).toInt()
    var thisAMonth = date.get(Calendar.MONTH).toInt()
    var thisADay = date.get(Calendar.DAY_OF_MONTH).toInt()

    val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view2, thisYear, thisMonth, thisDay ->
        // Display Selected date in textbox
        thisAMonth = thisMonth + 1
        thisADay = thisDay
        thisAYear = thisYear

        statusDateID.setText("Date: " + thisAMonth + "/" + thisDay + "/" + thisYear)
        val newDate:Calendar =Calendar.getInstance()
        newDate.set(thisYear, thisMonth, thisDay)

    }, thisAYear, thisAMonth, thisADay)
    dpd.show()

    mh.entryDate = date.timeInMillis
    println("DATE DATA: "+thisAYear+ " "+thisAMonth+" " + thisADay)
    println("DATE CHANGED MILLISECS = "+mh.entryDate)
}

mh.entryDate is defined as a global, and as a LONG. With the debugging println statements, both the DATE DATA and the DATE CHANGED MILLISECS show the current date.

like image 514
Tony Sherman Avatar asked Sep 06 '25 15:09

Tony Sherman


1 Answers

Just set date inside DatePickerDialog.OnDateSetListener method with mh.entryDate = newDate.timeInMillis

val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view2, thisYear, thisMonth, thisDay ->
    // Display Selected date in textbox
    thisAMonth = thisMonth + 1
    thisADay = thisDay
    thisAYear = thisYear

    statusDateID.setText("Date: " + thisAMonth + "/" + thisDay + "/" + thisYear)
    val newDate:Calendar =Calendar.getInstance()
    newDate.set(thisYear, thisMonth, thisDay)
    mh.entryDate = newDate.timeInMillis // setting new date
}, thisAYear, thisAMonth, thisADay)
dpd.show()
like image 112
Volodymyr Avatar answered Sep 09 '25 12:09

Volodymyr