Convert string to day of week (not exact date)

Franz Kafka picture Franz Kafka · Aug 14, 2013 · Viewed 18.3k times · Source

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.

Answer

René Link picture René Link · Aug 14, 2013

You can use SimpleDateFormat it can also parse the day for a specific Locale

public class Main {

    private static int parseDayOfWeek(String day, Locale locale)
            throws ParseException {
        SimpleDateFormat dayFormat = new SimpleDateFormat("E", locale);
        Date date = dayFormat.parse(day);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        return dayOfWeek;
    }

    public static void main(String[] args) throws ParseException {
        int dayOfWeek = parseDayOfWeek("Sunday", Locale.US);
        System.out.println(dayOfWeek);

        dayOfWeek = parseDayOfWeek("Tue", Locale.US);
        System.out.println(dayOfWeek);

        dayOfWeek = parseDayOfWeek("Sonntag", Locale.GERMANY);
        System.out.println(dayOfWeek);
    }

}