Friday, May 8, 2015

DatePicker Dialog Box in Android

A android dialog box containing an DatePicker
Class Overview
Public Constructors

public DatePickerDialog (Context context, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth)

Parameters
context The context the dialog is to run in.
callBack How the parent is notified that the date is set. or should set to null
year The initial year of the dialog.
monthOfYear The initial month of the dialog.
dayOfMonth The initial day of the dialog.

Public Methods
public DatePicker getDatePicker ()
Gets the DatePicker contained in this dialog.
Returns
  • The calendar view.

Below is the sample code for showing the Dialog box with Date

private SimpleDateFormat sdf;
private int year;
private int month;
private int day;


currentTime = new Date();
sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(currentTime));

final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);


final DatePickerDialog picker = new DatePickerDialog(this, null, year, month, day);
picker.setCancelable(true);
picker.setCanceledOnTouchOutside(true);
picker.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("Picker", "Correct behavior!");
// Show selected date in edittext box
System.out.println(new StringBuilder()
.append(picker.getDatePicker().getDayOfMonth()).append("/")
.append(picker.getDatePicker().getMonth()+1).append("/")
.append(picker.getDatePicker().getYear()).append("").toString());}});
         
picker.show();// show dialog box



Happy Coding !!