Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to day of week (not exact date)

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.

like image 724
Franz Kafka Avatar asked Aug 14 '13 12:08

Franz Kafka


People also ask

How to get day of week in c#?

Use DateTime. DayOfWeek property to display the current day of week. DayOfWeek wk = DateTime.

How to extract day from date in c#?

Use the DateTime. DayOfWeek or DateTimeOffset. DayOfWeek property to retrieve a DayOfWeek value that indicates the day of the week. If necessary, cast (in C#) or convert (in Visual Basic) the DayOfWeek value to an integer.

How do I convert a weekday to a string in Python?

Use the strftime() method of a datetime module to get the day's name in English in Python. It uses some standard directives to represent a datetime in a string format. The %A directive returns the full name of the weekday. Like, Monday, Tuesday.


2 Answers

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);
    }

}
like image 75
René Link Avatar answered Sep 21 '22 13:09

René Link


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
like image 34
tete Avatar answered Sep 20 '22 13:09

tete