8

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.

Franz Kafka
  • 10,623
  • 20
  • 93
  • 149
  • This is screaming `enum`. – rocketboy Aug 14 '13 at 13:01
  • 2
    Tip: Rather than pass around these strings for day-of-week, pass around [`java.time.DayOfWeek`](https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html) objects pre-defined in that enum. – Basil Bourque Mar 15 '17 at 19:56

10 Answers10

13

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
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
tete
  • 370
  • 3
  • 13
11

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

}
René Link
  • 48,224
  • 13
  • 108
  • 140
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. – Basil Bourque Mar 16 '17 at 05:02
6

For non-English day-of-week names, see Answer by tete.

tl;dr

 DayOfWeek.valueOf( "Monday".toUppercase() )  // `DayOfWeek` object. Works only for English language.
          .getValue()                         // 1

java.time

If your day-of-week names happen to be the full-length name in English (Monday, Tuesday, etc.), that happens to coincide with the names of the enum objects defined in the DayOfWeek enum.

Convert your inputs to all uppercase, and parse to get a constant object for that day-of-week.

String input = "Monday" ;
String inputUppercase = input.toUppercase() ;  // MONDAY
DayOfWeek dow = DayOfWeek.valueOf( inputUppercase );  // Object, neither a string nor a number.

Now that we have a full-feature object rather than a string, ask for the integer number of that day-of-week where Monday is 1 and Sunday is 7 (standard ISO 8601 definition).

int dayOfWeekNumber = dow.getValue() ;

Use DayOfWeek objects rather than strings

I urge you to minimize the use of either the name or number of day-of-week. Instead, use DayOfWeek objects whenever possible.

By the way, you can localize the day-of-week name automatically.

String output = DayOfWeek.MONDAY.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );

That localization is one-way only through the DayOfWeek class. To go the other direction in languages other than English, see the Answer by tete.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
4

I generally use an enum, though in this case your input has to be in proper case.

public enum DayOfWeek {
    Sunday(1),Monday(2),Tuesday(3),Wednesday(4),Thursday(5),Friday(6),Saturday(7);

    private final int value;

    DayOfWeek(int value) {

        this.value = value;
    }

    public int getValue() {

        return value;
    }

    @Override
    public String toString() {

        return value + "";
    }
}

Now, you can get the day of the week as follows:

String sunday = "Sunday";
System.out.println(DayOfWeek.valueOf(sunday));

This would give you following output:

1
Amar
  • 11,930
  • 5
  • 50
  • 73
  • 1
    Such an enum is now built into Java 8 and later, [`java.util.DayOfWeek`](https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html). Runs 1-7 for Monday-Sunday per [ISO 8601](https://en.wikipedia.org/wiki/ISO_week_date) standard. – Basil Bourque Aug 05 '17 at 01:16
1

You could do something like this:

    private static String getDayOfWeek(final Calendar calendar){
    assert calendar != null;
    final String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    return days[calendar.get(Calendar.DAY_OF_WEEK)-1];
}

Although it would probably be a good idea to declare the days of the week so you don't have to keep declaring them each time the method is called.

For the other way around, something like this:

    private static int getDayOfWeek(final String day){
    assert day != null;
    final String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    for(int i = 0; i < days.length; i++)
        if(days[i].equalsIgnoreCase(day))
            return i+1;
    return -1;
}
Josh M
  • 11,611
  • 7
  • 39
  • 49
1

Consider using a helper method like

public static int getDayOfWeekAsInt(String day) {
    if (day == null) {
        return -1;
    }
    switch (day.toLowerCase()) {
        case "monday":
            return Calendar.MONDAY;
        case "tuesday":
            return Calendar.TUESDAY;
        case "wednesday":
            return Calendar.WEDNESDAY;
        case "thursday":
            return Calendar.THURSDAY;
        case "friday":
            return Calendar.FRIDAY;
        case "saturday":
            return Calendar.SATURDAY;
        case "sunday":
            return Calendar.SUNDAY;
        default: 
            return -1;
    }
}

Please, note that using Strings with switch-case is only supported Java 7 onwards.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
0

Why not initialize what you want once?

private static final Map<String, Integer> weekDays;
static
{
    weekDays= new HashMap<String, Integer>();
    weekDays.put("Monday", Calendar.MONDAY);
    weekDays.put("Tuesday", Calendar.TUESDAY);
    // etc
}
Tala
  • 8,888
  • 5
  • 34
  • 38
0

Why not declare a Map:

Map<String, Integer> daysMap = new HashMap<String, Integer>();

daysMap.add("monday", 0);
daysMap.add("tuesday", 1);
//etc.

Then, when you need to search:

int dayId = daysMap.get(day.toLowerCase());

This should do what you need. You could even load the data from some file / database, etc.

Martin
  • 3,018
  • 1
  • 26
  • 45
0

If you are using java 8 :

import java.time.DayOfWeek;

Then simply use: DayOfWeek.[DAY].getValue()

System.out.println(DayOfWeek.MONDAY.getValue());
System.out.println(DayOfWeek.TUESDAY);
System.out.println(DayOfWeek.FRIDAY.getValue());

For older version check this answer: Convert string to day of week (not exact date)

Deepak Kumar
  • 1,669
  • 3
  • 16
  • 36
0

Use the names built into the DateFormatSymbols class as follows. This returns 0 for Sunday, 6 for Saturday, and -2 for any invalid day. Add your own error handling as you see fit.

private static final List dayNames = Arrays.asList(new DateFormatSymbols().getWeekdays());

public int dayNameToInteger(String dayName) {
    return dayNames.indexOf(dayName) - 1;
}
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110