0

I am newbie to android and trying to use DatePicker for my application. it's exists on the date.xml file. I made the AlertDialog box to show DatePicker using setView(R.layput.date) command. the AlertDialog box is appear when i click EditText. now I need to get changed Date to string from DatePicker when i click save buton of the AlertDialog box. how can i do that?

this is set of code of date.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_gravity="center_horizontal"></LinearLayout>

    <DatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/datePicker"
        android:layout_gravity="center_horizontal"
        android:layoutMode="clipBounds" />
</LinearLayout>

this is set of code AlertDialog box

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
final EditText edt = (EditText)findViewById(R.id.invo_date);
edt.setText(dateFormat.format(date));
edt.setInputType(0);
edt.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (!one){
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);

            AlertDialog.Builder alt = new AlertDialog.Builder(CreateInvoice.this);
            alt.setView(R.layout.date);
            alt.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    one = false;
                }
            });
            alt.setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // I need to get date aftre set Date form DatePicker to srting when I click Save button.

                }
            });
            alt.setCancelable(false);
            alt.show();
            one = true;
        }
        return true;
    }
});
Lilylakshi
  • 736
  • 7
  • 19
Dilanka Laksiri
  • 408
  • 3
  • 12

1 Answers1

0

Try below code :

int   day  = datePicker.getDayOfMonth();
int   month= datePicker.getMonth() + 1;
int   year = datePicker.getYear();

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String formatedDate = sdf.format(new Date(year, month, day));
Bhargav Thanki
  • 4,924
  • 2
  • 37
  • 43