Convert string to day of week (not exact date)

calendar, date, dayofweek, java, simpledateformat

Solution

java.time

For anyone interested in Java 8 solution, this can be achieved with something similar to this:

import static java.util.Locale.forLanguageTag;

import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

import java.time.DayOfWeek;
import org.junit.Test;

public class sarasa {

    @Test
    public void test() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE", forLanguageTag("es"));
        TemporalAccessor accessor = formatter.parse("martes"); // Spanish for Tuesday.
        System.out.println(DayOfWeek.from(accessor));
    }
}

Output for this is:

TUESDAY

Problem

I'm receiving a `String` which is a spelled out day of the week, e.g. Monday. Now I want to get the constant integer representation of that day, which is used in `java.util.Calendar`. Do I really have to do `if(day.equalsIgnoreCase("Monday")){...}else if(...){...}` on my own? Is there some neat method? If I dig up the `SimpleDateFormat` and mix that with the `Calendar` I produce nearly as many lines as typing the ugly if-else-to-infitity statetment.

Original source

Related problems