如何在Java中将日历的星期几从String转换为int?

时间:2019-04-18 08:47:37

标签: java android

我有名字,例如星期四。我想在日历对象中设置这一天,例如:

mCalendar.set(Calendar.DAY_OF_WEEK, 0);

但是问题在于,日期名称来自一个for循环,因此可以每次更改。因此,我想做的是一种可以将日期名称转换为int索引的方法。例如,如果日期名称是周日,则应为0赋予索引;如果星期四,则应赋予4

我尝试了以下代码:

 private void setNextIndexAlarm(Context context, int reminderId, String getCurrentDay) {
        int setDayOfWeek = stringToIntDayConverter(getCurrentDay);
        mCalendar.set(Calendar.DAY_OF_WEEK, setDayOfWeek);
        mCalendar.set(Calendar.MONTH, mMonth);
        mCalendar.set(Calendar.YEAR, mYear);
        mCalendar.set(Calendar.HOUR_OF_DAY, mHour);
        mCalendar.set(Calendar.MINUTE, mMinute);
        mCalendar.set(Calendar.SECOND, 0);
        new AlarmReceiver().createExactAlarm(context, mCalendar, reminderId);

    }

    private int stringToIntDayConverter(String getCurrentDay) {

        return 0;
    }

3 个答案:

答案 0 :(得分:2)

使用以下方法,该方法将返回可在日历中使用的int值。

public static int getDayOfWeek(String dayName) {
    int weekDay = 0;

    if (dayName.equalsIgnoreCase("sunday")) weekDay = 0;
    else if (dayName.equalsIgnoreCase("monday")) weekDay = 1;
    else if (dayName.equalsIgnoreCase("tuesday")) weekDay = 2;
    else if (dayName.equalsIgnoreCase("wednesday")) weekDay = 3;
    else if (dayName.equalsIgnoreCase("thursday")) weekDay = 4;
    else if (dayName.equalsIgnoreCase("friday")) weekDay = 5;
    else if (dayName.equalsIgnoreCase("satday")) weekDay = 6;

    return weekDay;
}

答案 1 :(得分:0)

您可以使用自己的枚举

enum Day{
        MONDAY,
        TUESDAY,
        WEDNESDAY,
        THURSDAY,
        FRIDAY,
        SATURDAY,
        SUNDAY
    }

所以,天数取决于班级的顺序。

Day.MONDAY.ordinal()在这种情况下显示0。

答案 2 :(得分:0)

Map<String, Int> dayOfWeek = new HashMap<String, Int>();
dictionary.put("monday", 0);
// other days


// to get the value
int value = dictionary.get("monday");

如果您拥有Java 9或更高版本

Map<String, Int> dayOfWeek = Map.of(
    "monday", 2,
    "tuesday", 1 // etc
);

或者您知道,只需使用Kotlin