前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JAVA 星座/生肖/年龄 计算器

JAVA 星座/生肖/年龄 计算器

作者头像
前Thoughtworks-杨焱
发布2021-12-08 08:58:49
1K0
发布2021-12-08 08:58:49
举报
文章被收录于专栏:杨焱的专栏

去年看五行,今年看星座,星座计算代码,存起来,会用到的:

代码语言:javascript
复制
/**
 * 星座/生肖/年龄 计算器
 * Created by fengyunhe 2015/8/12.
 */
public class ConstellationUtils {

    public static final String[] zodiacArr = {"猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊"};

    public static final String[] constellationArr = {"水瓶座", "双鱼座", "牡羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座",
            "天蝎座", "射手座", "魔羯座"};

    public static final int[] constellationEdgeDay = {20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22};

    /**
     * 根据日期获取生肖
     *
     * @return
     */
    public static String date2Zodica(Calendar time) {
        return zodiacArr[time.get(Calendar.YEAR) % 12];
    }

    /**
     * 根据日期获取星座
     *
     * @param time
     * @return
     */
    public static String date2Constellation(Calendar time) {
        int month = time.get(Calendar.MONTH);
        int day = time.get(Calendar.DAY_OF_MONTH);
        if (day < constellationEdgeDay[month]) {
            month = month - 1;
        }
        if (month >= 0) {
            return constellationArr[month];
        }
        //default to return 魔羯
        return constellationArr[11];
    }


    /**
     * 计算年龄
     *
     * @param birthCal
     * @return 如果生日大于今天的日期,则返回-1
     */
    public static int calcAge(Calendar birthCal) {
        Calendar flightCal = Calendar.getInstance();
        int y = flightCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);
        int m = flightCal.get(Calendar.MONTH) - birthCal.get(Calendar.MONTH);
        int d = flightCal.get(Calendar.DATE) - birthCal.get(Calendar.DATE);
        if (y < 0) {
            return 0;
        }
        if (m < 0 || m == 0 && d < 0) { //月份不够一年
            y--;
        }

        if (y < 0) {
            return -1;
        }
        return y;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-08-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档