Android 生日倒计时天数计算

Android 生日倒计时天数计算

需求一:计算距离下一个生日还剩多少天
分析:
正常日期:下一年的今天-今天,然后计算
特殊日期(2.29):下一闰年的今天-今天,然后计算
前提是本年事件还没有结束,才可以这样计算!
如果你要计算其他日期,例如明年的国庆,只需要把闰年判断去掉即可

 /**
     * 距离生日还有多少天(距离下一年或本年)
     *
     * @param targetMonth 生日的月份
     * @param targetDay   生日的天
     */
    public static int getTargetSurplusDay(int targetMonth, int targetDay) {
        boolean isSpend;//本年是否已过
        int targetYear;//生日年
        Calendar nowTime = Calendar.getInstance();
        int nowYear = nowTime.get(Calendar.YEAR);
        int nowMonth = nowTime.get(Calendar.MONTH);
        int nowDay = nowTime.get(Calendar.DAY_OF_MONTH);
        if (nowMonth == targetMonth && nowDay == targetDay) {//生日为今天
            return 0;
        } else if (nowMonth > targetMonth) {//生日已过(下一年)
            isSpend = true;
        } else {
               if (nowMonth == targetMonth && nowDay > targetDay)//生日已过(下一年)
                isSpend = true;
            else //生日未到(本年)
                isSpend = false;
        }
        if (targetMonth == 2 && targetDay == 29) {//闰年2.29就要下一个闰年
            boolean isRunYear = true;
            int rYear = nowYear;
            while (isRunYear) {
                rYear++;
                if (rYear % 4 == 0 && rYear % 100 != 0 || rYear % 400 == 0)
                    isRunYear = false;
            }
            targetYear = isSpend ? rYear : rYear;
        } else
            targetYear = isSpend ? nowYear + 1 : nowYear;
        Calendar targetTime = Calendar.getInstance();
        targetTime.set(targetYear, targetMonth - 1, targetDay);//月份是从0开始的,所以要减1
        long targetMillis = targetTime.getTimeInMillis() - nowTime.getTimeInMillis();
        return (int) (targetMillis / (24 * 60 * 60 * 1000));
    }

需求二:
计算两个时间相差多少个月
公式:年减年*12+月减月
例如:2000年10月和2020年9月进行比较
运用:(2020-2000)*12+9-10=239个月

需求三:
判断当前时间是否在范围内(限今日、不跨天)

/**
     * 判断当前时间是否在范围
     * @return 0在范围 1未到  2已过
     */
    public static int getTimeIsRange(int beginHour, int beginMinute, int endHour, int endMinute) {
        int type = 0;
        Calendar nowTime = Calendar.getInstance();
        int nowYear = nowTime.get(Calendar.YEAR);
        int nowMonth = nowTime.get(Calendar.MONTH);
        int nowDay = nowTime.get(Calendar.DAY_OF_MONTH);
        Calendar beginTime = Calendar.getInstance();
        beginTime.set(nowYear, nowMonth, nowDay, beginHour, beginMinute);
        Calendar endTime = Calendar.getInstance();
        endTime.set(nowYear, nowMonth, nowDay, endHour, endMinute);
        if (nowTime.before(beginTime)) {
            type = 1;
        } else if (nowTime.after(endTime)) {
            type = 2;
        } else
            type = 0;
        return type;
    }
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值