Convert string to day of week (not exact date)

ぃ、小莉子 提交于 2019-12-01 15:17:21

问题


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.


回答1:


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

}



回答2:


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



回答3:


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



回答4:


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



回答5:


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.




回答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?

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

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.




回答7:


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
}



回答8:


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.




回答9:


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)




回答10:


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


来源:https://stackoverflow.com/questions/18232340/convert-string-to-day-of-week-not-exact-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!