遇到的情况
最近一直在搞会员营销相关系统,生日对于大多数会员系统来说都是一个比较好的运营点,几乎所有的系统都会在会员生日当天提供一些营造优惠和祝福信息触达,用来提升用户对品牌的认可和用户粘性,甚至提升用户的复购率或者沉默用户的活跃度。
今天是否用户生日
判断用户是否当天生日,这个一个很常见的场景,而且几乎没什么难度,怎么去更方便更快的实现这个场景呢
基础数据存储
大多数的系统在存储用户生日都是使用 年月日 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
总结
很简单的一个判断,采用类似年份差值的计算方式,会存在闰年差异,导致误判;另外两种方式都可以得到准确判断,可以按照个人习惯采用。