标签:
我使用redis的setbit和bitcount来进行这个操作。需要注意的是setbit修改的是bit位置,而bitcount检查的是byte位置,两者相差有8的倍数。伪代码如下
//计算两个日期之间的差值 long daysBetween(Date date1,Date date2) { Calendar cal = Calendar.getInstance(); cal.setTime(date1); long time1 = cal.getTimeInMillis(); cal.setTime(date2); long time2 = cal.getTimeInMillis(); long between_days=(time2-time1)/(1000*3600*24); return Long.parseLong(String.valueOf(between_days)); } //根据日期,得到一个整数位数 long dayIndex(Date date1) throws ParseException { String d0 = "2010-01-01 00:00:00"; Date date0 = simpledate.parse(d0); return daysBetween(date0, date1);//取参数日期与2010年1月1日的差值 } //调用redis的setbit方法,键为用户名,位置为天数乘8,值为true boolean setUserLoginday(Jedis redis, String user, Date currentDate) { long day_position = dayIndex(currentDate); //乘以8的原因是这个操作修改的是bit位置 //然而bitcount修改操作的是byte位置 return redis.setbit(user, day_position * day_multiplication_factor, true); } //调用redis的bitcount方法计算,键为用户名,在两个日期之间登录的天数 long countUserLoginDays(Jedis redis, String user, Date fromdate, Date todate) throws ParseException { long from_day_position = DataTransformer.dayIndex(fromdate); long to_day_position = DataTransformer.dayIndex(todate); return redis.bitcount(key, from_day_position, to_day_position); }
标签:
原文地址:http://my.oschina.net/u/2242064/blog/402961