一个简单的星期枚举类及应用

/**
 * 枚举类
 */
public enum WeekEnum {
    SUN("周日"),
    MON("周一"),
    TUE("周二"),
    WED("周三"),
    THU("周四"),
    FRI("周五"),
    SAT("周六");

    private String weekday;

    WeekEnum(String weekday) {
        this.weekday = weekday;
    }

    public String getWeekday() {
        return this.weekday;
    }
}

/**
 * 获取今天是星期几
 */
class Test{
    public static void main(String[] args) {
        Date today = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);

        // 获取星期索引, 0 代表周日
        int weekIndex = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (weekIndex < 0) {
            weekIndex = 0;
        }

        String weekday = WeekEnum.values()[weekIndex].getWeekday();
        System.out.println(weekday);

        // 当然也可以输出英文的星期
        WeekEnum enWeekday = WeekEnum.values()[weekIndex];
        System.out.println(enWeekday.toString());
    }
}

 

你可能感兴趣的:(Java,数据结构与算法)