Convert string to day of week (not exact date)

I get String , which is the prescribed day of the week, for example. Monday. Now I want to get a constant integer representation of this day, which is used in java.util.Calendar .

Do I need to do if(day.equalsIgnoreCase("Monday")){...}else if(...){...} own? Is there any neat method? If I dig SimpleDateFormat and mix that with Calendar , I create almost as many lines as I type the ugly if-else-to-infitity value.

+7
java date dayofweek calendar simpledateformat
source share
10 answers

You can use SimpleDateFormat , it can also analyze 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); } } 
+9
source share

I usually use an enumeration, although in this case your input should be in the correct 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 will give you the following result:

 1 
+3
source share

java.time

For anyone interested in the 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)); } } 

The output for this is:

 TUESDAY 
+2
source share

You can 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 be nice to declare the days of the week, so you do not need to constantly declare them every time the method is called.

On the other hand, 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; } 
+1
source share

Consider using a helper method, for example

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

Note that using strings with switch-case is only supported by Java 7.

+1
source share

For names not related to the English day of the week, see Reply from tete .

TL; DR

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

java.time

If the names of your day of the week are a full-sized name in English (Monday, Tuesday, etc.), this matches the names of the enumeration objects defined in DayOfWeek enum.

Convert your entries to all uppercase letters and analyze to get a permanent object for that day of the 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 fully functional object, not a string, ask for the integer of this day of the week, where Monday is 1 and Sunday is 7 (standard ISO 8601 ).

 int dayOfWeekNumber = dow.getValue() ; 

Use DayOfWeek objects, not strings

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

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

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

This localization is one-way only through the DayOfWeek class. To go in a different direction in languages ​​other than English, see Answer tet .


About java.time

The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy time classes such as java.util.Date , Calendar and SimpleDateFormat .

The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.

To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .

Where to get java.time classes?

  • Java SE 8 and SE 9 and later
    • Built in.
    • Part of the standard Java API with integrated implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Most of the functionality of java.time has been ported to Java 6 and 7 in ThreeTen-Backport .
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) specifically for Android.
    • See How to use ThreeTenABP ....

The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and more .

+1
source share

Why not initialize what you need?

 private static final Map<String, Integer> weekDays; static { weekDays= new HashMap<String, Integer>(); weekDays.put("Monday", Calendar.MONDAY); weekDays.put("Tuesday", Calendar.TUESDAY); // etc } 
0
source share

Why not declare a card:

 Map<String, Integer> daysMap = new HashMap<String, Integer>(); daysMap.add("monday", 0); daysMap.add("tuesday", 1); //etc. 

Then, when you need to do a search:

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

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

0
source share

If you are using java 8:

 import java.time.DayOfWeek; 

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

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

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

0
source share

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; } 
0
source share

All Articles