Search code examples
javaandroiddate-formattingandroid-datepickerandroid-date

How do I convert my date string to a custom date format?


I am currently working on creating a custom date format such that it is supposed to show as "Monday, April 8, 2019 " but whenever I pick from dialog and apply simple date format, it returns the date with abbreviated month and time (which I don't need). any idea how I can update my code to get it to work in the above format? Here's my code :

@Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

        String date = (++monthOfYear)+" "+dayOfMonth+", "+year;
        SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM dd yyyy");
        dateFormat.format(new Date());
        Date convertedDate = new Date();
        try {
            convertedDate = dateFormat.parse(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        myDate.setText(convertedDate.toString());
    }

Solution

  • To achieve such a format: Monday, April 8, 2019 you have to format the date like this (source):

    SimpleDateFormat mDateFormat = new SimpleDateFormat("EEEE, MMMMM dd, yyyy");
    myDate.setText(mDateFormat.format(convertedDate));
    

    Good luck


    I would do something like this:

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        Calendar mDate = Calendar.getInstance();
        mDate.set(year, monthOfYear, dayOfMonth);
        SimpleDateFormat mDateFormat = new SimpleDateFormat("EEEE, MMMMM dd, yyyy");
        myDate.setText(mDateFormat.format(mDate.getTime()));
    }