欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-16 16:54:42
...
/**
 * 枚举类
 */
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 枚举类