Rence
Rence

Reputation: 2950

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?

Upvotes: 3

Views: 3776

Answers (2)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

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

Upvotes: 6

Michael
Michael

Reputation: 44250

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.

Upvotes: 4

Related Questions