Create date Dialog - Android android.widget

Android examples for android.widget:DatePicker

Description

Create date Dialog

Demo Code

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.widget.DatePicker;
import android.widget.TextView;

public class Main {

  public static Dialog dateDialog(Context context, final TextView et) {
    Dialog dialog = null;/*from w  w w . java 2  s  .c  om*/
    Calendar c = Calendar.getInstance();
    String time = et.getTag().toString();
    if (time != null && !"".equals(time)) {
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      try {
        Date d = format.parse(time);
        c.setTime(d);
      } catch (ParseException e) {
        e.printStackTrace();
      }
    }
    dialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
      public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {
        et.setText(year + " " + (month + 1) + " " + dayOfMonth);
        Calendar cs = Calendar.getInstance();
        cs.set(Calendar.YEAR, year);
        cs.set(Calendar.MONTH, month);
        cs.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        et.setTag(format.format(cs.getTime()));
      }
    }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
    return dialog;
  }
}

Related Tutorials