In Java an DatePickerDialog can be use such as:
final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog dpd = new DatePickerDialog(getActivity(),new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // Display Selected date in textbox lblDate.setText(""+ dayOfMonth+" "+MONTHS[monthOfYear] + ", " + year); } }, year, month,day); dpd.show();
How does Kotlin's DatePickerDialog use look like?
Get the references of Views in layout file. Create an OnDateSetListener. We shall use Calendar object to store the selected date, and we shall call a method to update a TextView with the selected date. Set OnClickListener to a Button, and On Click, display DatePickerDialog to pick the date.
We can create a DatePicker control in two ways either manually in XML file or create it in Activity file programmatically. First we create a new project by following the below steps: Click on File, then New => New Project. After that include the Kotlin support and click on next.
As Kotlin is interoperable with Java, we will be using the Java utility class and Simple Date Format class in order to get the current local date and time.
It would look something like this:
val c = Calendar.getInstance() val year = c.get(Calendar.YEAR) val month = c.get(Calendar.MONTH) val day = c.get(Calendar.DAY_OF_MONTH) val dpd = DatePickerDialog(activity, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth -> // Display Selected date in textbox lblDate.setText("" + dayOfMonth + " " + MONTHS[monthOfYear] + ", " + year) }, year, month, day) dpd.show()
this was done by simply copying and pasting the code into a kotlin file in android studio. I would strongly recommend using it.
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView: TextView = findViewById(R.id.textView_date) textView.text = SimpleDateFormat("dd.MM.yyyy").format(System.currentTimeMillis()) var cal = Calendar.getInstance() val dateSetListener = DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth -> cal.set(Calendar.YEAR, year) cal.set(Calendar.MONTH, monthOfYear) cal.set(Calendar.DAY_OF_MONTH, dayOfMonth) val myFormat = "dd.MM.yyyy" // mention the format you need val sdf = SimpleDateFormat(myFormat, Locale.US) textView.text = sdf.format(cal.time) } textView.setOnClickListener { DatePickerDialog(this@MainActivity, dateSetListener, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show() } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With