实现效果
传入时间类型的对象,就可以获取对应的星座id和星座名称:
实现代码
封装星座枚举类,并提供静态方法:
import java.time.LocalDate;
import java.util.Date;
/**
* @author lzp
* @Description: 星座枚举
*/
public enum ConstellationEnum {
// 白羊座、金牛座、双子座、巨蟹座、狮子座、处女座、天秤座、天蝎座、射手座、摩羯座、水瓶座、双鱼座
ARIES(1, "白羊座"),
TAURUS(2, "金牛座"),
GEMINI(3, "双子座"),
CANCER(4, "巨蟹座"),
LEO(5, "狮子座"),
VIRGO(6, "处女座"),
LIBRA(7, "天秤座"),
SCORPIO(8, "天蝎座"),
SAGITTARIUS(9, "射手座"),
CAPRICORN(10, "摩羯座"),
AQUARIUS(11, "水瓶座"),
PISCES(12, "双鱼座");
public Integer getValue() {
return value;
}
public String getTitle() {
return title;
}
public final Integer value;
public final String title;
ConstellationEnum(Integer value, String title) {
this.value = value;
this.title = title;
}
/**
* 天数差
*/
private static int[] dayArr = new int[]{20, 19, 21, 20, 21, 22, 23, 23, 23, 24, 23, 22};
private final static ConstellationEnum[] constellationArr = new ConstellationEnum[]{
CAPRICORN, AQUARIUS, PISCES, ARIES, TAURUS, GEMINI, CANCER, LEO, VIRGO, LIBRA, SCORPIO, SAGITTARIUS, CAPRICORN
};
/**
* 通过出生日期获取星座
*
* @param birthdate date类型的出生日期
*/
public static ConstellationEnum getByBirthdate(Date birthdate) {
int month = birthdate.getMonth() + 1;
int day = birthdate.getDate();
return getByBirthdate(month, day);
}
/**
* 通过出生日期获取星座
*
* @param birthdate date类型的出生日期
*/
public static ConstellationEnum getByBirthdate(LocalDate birthdate) {
int month = birthdate.getMonth().getValue();
int day = birthdate.getDayOfMonth();
return getByBirthdate(month, day);
}
/**
* 对应日月获取星座
*
* @param month 月份
* @param day 日
*/
public static ConstellationEnum getByBirthdate(int month, int day) {
return day < dayArr[month - 1] ? constellationArr[month - 1] : constellationArr[month];
}
@Override
public String toString() {
return "当前星座{" +
"value=" + value +
", title='" + title + '\'' +
'}';
}
}
编写测试类
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
/**
* @Author: lzp
* @description: 星座测试类
* @Date: 2022/7/24
*/
public class Demo {
public static void main(String[] args) throws ParseException {
// 日月作为参数调用
System.out.println(ConstellationEnum.getByBirthdate(1, 2));
// LocalDate类型作为参数调用
System.out.println(ConstellationEnum.getByBirthdate(LocalDate.of(1998, 5, 20)));
// Date类型作为参数调用
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
System.out.println(ConstellationEnum.getByBirthdate(df.parse("1998-9-9")));
}
}