当天是否生日的判断方法比较

遇到的情况

最近一直在搞会员营销相关系统,生日对于大多数会员系统来说都是一个比较好的运营点,几乎所有的系统都会在会员生日当天提供一些营造优惠和祝福信息触达,用来提升用户对品牌的认可和用户粘性,甚至提升用户的复购率或者沉默用户的活跃度。

今天是否用户生日

判断用户是否当天生日,这个一个很常见的场景,而且几乎没什么难度,怎么去更方便更快的实现这个场景呢

基础数据存储

大多数的系统在存储用户生日都是使用 年月日 yyyy-MM-dd的格式,使用一个生日字段做存储不做其他冗余字段。

判断方式

1.年度差值比对

public static void main(String[] args) {

        LocalDate brithday = LocalDate.parse("2009-12-19");
        boolean brithday1 = isBrithday(brithday);
        System.out.println("today is brithday:"+brithday1);
    }
    public static boolean isBrithday(LocalDate brithday){
        //1.年度差值计算
        LocalDate now = LocalDate.now();
        int nowYear = now.getYear();
        int brithYear = brithday.getYear();
        LocalDate nowBrith = brithday.plusYears(nowYear-brithYear);
        return nowBrith.equals(now);
    }

2.月份+日期判断

public static boolean isBrithday(LocalDate brithday){
     LocalDate now = LocalDate.now();
     int brithMonth = brithday.getMonthValue();
     int brithdayDayOfMonth = brithday.getDayOfMonth();
     int nowDayOfMonth = now.getDayOfMonth();
     int nowMonth = now.getMonthValue();
    return (brithMonth==nowMonth && brithdayDayOfMonth==nowDayOfMonth);
 }

3.当年第几天

    public static boolean isBrithday(LocalDate brithday){
     return brithday.getDayOfYear()==LocalDate.now().getDayOfYear();

闰年问题

年度差值计算:

验证:用户输入生日为2020-02-29,今天日期2023-02-28,结果存在误判。
输出结果:

brithday is 2020-02-29
nowBrith is 2023-02-28
today is brithday:true

月份+日期判断

验证:用户输入生日为2020-02-29,今天日期2023-02-28,结果不存在误判。
输出结果:

brithday is 2020-02-29
now is 2023-02-28
today is brithday:false

直接比对当年第几天

验证:用户输入生日为2020-02-29,今天日期2023-02-28,结果不存在误判。
输出结果:

brithday is 2020-02-29
now is 2023-02-28
today is brithday:false

总结

很简单的一个判断,采用类似年份差值的计算方式,会存在闰年差异,导致误判;另外两种方式都可以得到准确判断,可以按照个人习惯采用。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值