Search code examples
javajava-timedayofweek

Java DayOfWeek convert Day Name (String) to Day Number


I am trying to convert String value of a weekday to a Number.

I was looking into Enum DayOfWeek (https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html), but it does not work the way I expected.

Code

String n = "MONDAY";

System.out.println(n); //prints MONDAY
System.out.println(DayOfWeek.valueOf(n)); //also prints MONDAY - should print 1

How can I get the corresponding number from my string instead?


Solution

  • DayOfWeek

    Here you need to get the day-of-week int value. For that you need to use DayOfWeek.valueOf and DayOfWeek::getValue(). This works if your string inputs use the full English name of the day of week, as used on the DayOfWeek enum objects.

     System.out.println(DayOfWeek.valueOf(n).getValue());
    

    It returns the day-of-week, from 1 (Monday) to 7 (Sunday).