3

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?

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
Rence
  • 2,900
  • 2
  • 23
  • 40

2 Answers2

6

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).

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
4

Look at the JavaDoc. Use getValue:

Gets the day-of-week int value.

The values are numbered following the ISO-8601 standard, from 1 (Monday) to 7 (Sunday).

In your case

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

DayOfWeek is an enum that doesn't override toString, so the default behaviour is to print the name of the enum constant, which is 'MONDAY'. That's why you saw that behaviour.

Michael
  • 41,989
  • 11
  • 82
  • 128