Search code examples
androidstringsimpledateformatdate-formattingdayofweek

SimpleDateFormat String to Day of Week


I've got a SQLite Database in Android where the date of an specific Event is saved as a String. I got the Date by a DatePickerDialog.

My Events get shown in an ListView and for that I want to order them by date and get the day of week from every String.

I know I have to convert my String to SimpleDateFormat and then get the day and make Event comparable. But all I get is a ParseException.

That's the String I insert into my Database:

 private void handleDateDialog() {
    setDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int day = cal.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog dialog = new DatePickerDialog(CreateEvent.this,android.R.style.Theme_Holo_Light_Dialog_MinWidth,dateSetListener,year,month,day);

            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.show();
        }
    });

    dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month += 1;
            String input = day + "-" + month + "-" + year;
            dateSelected.setText(input);
        }
    };
}

This is what I got from Stack Overflow by reading other questions:

public String getDayOfWeek(){
    String eventDate = this.getDate();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    try {
        Date myDate = dateFormat.parse(eventDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    dateFormat.applyPattern("EE");
    String dayofweek = dateFormat.format(date);
    return dayofweek;
}

And this is how I try to get the new String dayOfWeek into my ListView:

try {
    holder.day_of_week.setText(individualEvent.getDayOfWeek());
} catch (Exception e) {
    e.printStackTrace();
}

But I always get this error in Android Monitor:

java.lang.IllegalArgumentException: Cannot format given Object as a Date

So, I assume I've made something wrong in my Database.

When show my date String it shows like this: 28-10-2017

I don't know why this isn't formatable.


Solution

  • You need to change your code as :

    public String getDayOfWeek(){
        String eventDate = this.getDate();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
        try {
            Date myDate = dateFormat.parse(eventDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        dateFormat.applyPattern("EE");
        String dayofweek = dateFormat.parse(myDate);
        return dayofweek;
    }