8

我收到的String是一周中的某一天,例如星期一。现在我想得到那天的常量整数表示,它在java.util.Calendar.

我真的必须自己做if(day.equalsIgnoreCase("Monday")){...}else if(...){...}吗?有什么巧妙的方法吗?如果我挖掘并将其与我SimpleDateFormat混合,Calendar我产生的行数几乎与输入丑陋的 if-else-to-infitity 语句一样多。

4

10 回答 10

11

您可以使用SimpleDateFormat它也可以解析特定的日期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);
    }

}
于 2013-08-14T13:01:03.937 回答
9

java.time

对于对 Java 8 解决方案感兴趣的任何人,都可以通过类似的方式来实现:

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

输出是:

TUESDAY
于 2017-03-15T12:39:00.633 回答
4

我通常使用枚举,但在这种情况下,您的输入必须是正确的。

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

现在,您可以按如下方式获取星期几:

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

这将为您提供以下输出:

1
于 2013-08-14T13:18:20.870 回答
3
于 2017-03-16T07:11:20.640 回答
1

考虑使用辅助方法,例如

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

请注意,switch-case仅 Java 7 及更高版本支持使用字符串。

于 2013-08-14T13:07:45.470 回答
1

你可以这样做:

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

尽管声明星期几可能是个好主意,这样您就不必在每次调用该方法时都继续声明它们。

相反,类似这样的事情:

    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;
}
于 2013-08-14T13:00:32.240 回答
0

为什么不初始化一次你想要的?

private static final Map<String, Integer> weekDays;
static
{
    weekDays= new HashMap<String, Integer>();
    weekDays.put("Monday", Calendar.MONDAY);
    weekDays.put("Tuesday", Calendar.TUESDAY);
    // etc
}
于 2013-08-14T13:00:56.837 回答
0

为什么不声明一个地图:

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

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

然后,当您需要搜索时:

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

这应该做你需要的。您甚至可以从某个文件/数据库等加载数据。

于 2013-08-14T13:04:00.217 回答
0

使用类中内置的名称DateFormatSymbols,如下所示。这将返回 0 代表星期日,6 代表星期六,以及 -2 代表任何无效的一天。添加您认为合适的错误处理。

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

public int dayNameToInteger(String dayName) {
    return dayNames.indexOf(dayName) - 1;
}
于 2017-06-28T03:59:31.007 回答
0

如果您使用的是 java 8 :

import java.time.DayOfWeek;

然后简单地使用: DayOfWeek.[DAY].getValue()

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

对于旧版本,请检查此答案: Convert string to day of week (not exact date)

于 2017-06-28T02:41:47.003 回答