1、传入年龄段,两个值,一个最小值,一个最大值,然后获取该年龄段的两个时间戳:
(1)处理时间方法:
1 /** 2 * 根据年龄获取时间戳(开始年龄key取0,返回一年最后一秒时间戳,时间戳大;反之结束年龄获取一年初始时间戳) 3 * 4 * @param age 年龄 5 * @param key 判断键,0-年龄小,1-年龄大 6 * 7 * @return 时间戳 8 */ 9 private Long getBirthTime(Integer age, Integer key) { 10 11 DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 12 Date d = new Date(); 13 Calendar c = Calendar.getInstance(); 14 c.setTime(d); 15 c.add(Calendar.YEAR, 0 - age); 16 17 if (key == 0) { 18 c.set(Calendar.MONTH, 11);//十二月 19 c.set(Calendar.DATE, 31); 20 c.set(Calendar.HOUR, 23); 21 c.set(Calendar.MINUTE, 59); 22 c.set(Calendar.SECOND, 59); 23 } else { 24 c.set(Calendar.MONTH, 0);//一月 25 c.set(Calendar.DATE, 1); 26 c.set(Calendar.HOUR, 0); 27 c.set(Calendar.MINUTE, 0); 28 c.set(Calendar.SECOND, 0); 29 } 30 31 Date birthDate = c.getTime(); 32 String a = format.format(birthDate); 33 return DatetimeUtils.convertStartDateToTimestamp(a); 34 }
(2)调用:
Long beginAge;
Long endAge;
beginAge = getBirthTime(req.getLowValue().intValue(),0);
endAge = getBirthTime(req.getHighValue().intValue(),1);
2、传入时间戳获取对应的月份:
(1)处理时间方法:
1 private Integer getBirthTime(Long timeStamp) { 2 try { 3 Date date = new Date(timeStamp * 1000); 4 Calendar c = Calendar.getInstance(); 5 c.setTime(date); 6 return c.get(Calendar.MONTH) + 1; 7 } catch (Exception e) { 8 e.printStackTrace(); 9 } 10 return 0; 11 }
(2)调用:
Integer birthday;
//获取日期的月份
birthday = getBirthTime(1514735999L);
(3)数据库的表中存在birthday字段,以时间戳形式存放,截取其中月份:
select *
FROM member_info
WHERE
FROM_UNIXTIME(`birthday`,'%m') = 7
(4)在Java中拼接成条件字符串:
String sql = "FROM_UNIXTIME(`birthday`,'%m') = " + birthMonth;