Search code examples
androiddatedatepickerandroid-dateutils

How to remove date from DatePicker toString method?


I have just started learning android through Android's big nerd ranch guide. I have written a simple program in android that let's user select a date. While printing the date using getDate().toString() method, I am also getting the Time. I want to remove that time column. So far, I have tried passing back datePicker, date, month, or year through an intent, but its not working. This is what my Code for DatePicker looks like:

public Dialog onCreateDialog(Bundle savedInstanceState)
    {
       // super.onCreate(savedInstanceState);
        date=(Date) getArguments().getSerializable(Extra_Tag);
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH);
        int day=calendar.get(Calendar.DAY_OF_MONTH);

        View view=getActivity().getLayoutInflater().inflate(R.layout.date_picker, null);
         DatePicker datePicker= (DatePicker) view.findViewById(R.id.date_button);
        datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                date=new GregorianCalendar(year,monthOfYear,dayOfMonth).getTime();
                getArguments().putSerializable(Extra_Tag,date);
            }
        });
        return new AlertDialog.Builder(getActivity()).setView(view).setTitle(R.string.date_picker).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                sendResult(Activity.RESULT_OK);
            }
        }).create();
    }
    private void sendResult(int resultCode)
    {
        if(getTargetFragment()==null)
        {
            return;
        }
        Intent i=new Intent();
        i.putExtra(Extra_Tag,date);
        getTargetFragment().onActivityResult(getTargetRequestCode(),resultCode,i);

    }

Here's the calling activity looks like:

public void onActivityResult(int requestCode, int resultCode,Intent data)
{
    if(resultCode!= Activity.RESULT_OK)
        return;
    if(requestCode==Request_code)
    {
        Date date=(Date) data.getSerializableExtra(Extra_Tag);
        crime.setDate(date);
        dateButton.setText(crime.getDate().toString());
    }
}

For Instance, this is what sample output looks like Fri JUL 17 22:46:42 CDT 2015. My motive is to just display the date by removing the time. Please Explain in Detail. Thank you


Solution

  • You can convert your date by writing just two lines

    For Example

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
    // Set your date format
    String currentData = sdf.format(date);