天天看点

mysql 对于年月日日期的比较bug记录

        记录一下mysql的问题,在前段日期传过来是2017-01-01的格式,我要在数据库比较日期,假设是年龄,我可以在mysql语句中拼查询,如下:

SELECT * FROM `retire_infor` re
where re.birtyday >= '1956-01-01' and re.birtyday <= '1958-01-01'
           

        但这样查询你会发现只能查询到1956和1957的,所谓的<=1958,1958没有查询到,参考别人的博客才知道,日期的比较,如果是年月日的形式默认为2017-01-01 00:00:00的形式,要想包括1958,必须为1958-01-01 23:59:59才行.工具类对于年龄,前端传几岁,后台进行拼接方法如下:

/**
	 * 根据规则计算开始时间 年龄为区间段,根据传入的年龄比较出生日期 因为日期拼接2017-01-01,查询时默认为2017-01-01
	 * 00:00:00,如果是结尾的日期,应该变成2017-01-01 23:59:59,或者加一个也是可以的
	 * 
	 * @param ageBegin
	 * @return
	 * @author [email protected]
	 * @createTime 2016年12月15日 上午10:57:12
	 */
	public static Date getBegin(Integer ageBegin, Boolean ifEnd) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		// 获取当前系统的年份
		Calendar c = Calendar.getInstance();
		c.add(Calendar.YEAR, -ageBegin);
		String beginYearString = sdf.format(c.getTime());

		String dateCompar = "";
		if (ifEnd) {
			dateCompar = sdf.format(c.getTime()) + "-01-01 00:00:00";
		} else {
			dateCompar = sdf.format(c.getTime()) + "-01-01 23:59:59";// 结束时间应该为23:59:59
		}

		Date beginDate = null;
		beginDate = parseBirDate(dateCompar);
		LogUtil.info("开始时间为" + beginDate.toString());
		return beginDate;

	}
           

      注:如果要比较年份的话,sql语句可以完成:

SELECT * FROM `retire_infor` re
where re.birtyday >= '1956-01-01' and re.birtyday <= DATE_ADD('1958-01-01',INTERVAL 1 YEAR)
           

继续阅读