最近在项目中碰到一个坑和大家分享一下,在mysql数据库时间使用时间戳,在实体类中也是用的Timestamp类型,在根据时间查询的时候,不要用Date类型直接查找会报找不到属性的异常
用以下方法就可以:
// 全局变量publicstaticfinal String TIME_FULL_SPRIT="yyyy-MM-dd HH:mm:ss";/** * 时间转换成字符串 * * @param date 日期 * @param formartStr 格式 * @retur */publicstatic StringdateToString(Date date, String formartStr){ String strDate= null;if(date!= null&& formartStr!= null&&!"".equals(formartStr)){ SimpleDateFormat sdf=newSimpleDateFormat(formartStr); strDate= sdf.format(date);}return strDate;}// 调用日期转字符串方法,时间戳格式也有严格要求,这个不懂的可以自行百度 String now=dateToString(newDate(), TIME_FULL_SPRIT); Timestamp time= Timestamp.valueOf(now);
比较两个时间戳,不能直接用大于小于,要用以下方法:
Timestamp now= Timestamp.valueOf(dateToString(newDate(), TIME_FULL_SPRIT)); Timestamp endAt= Timestamp.valueOf(dateToString(newDate(), TIME_FULL_SPRIT));if(now.getTime()>=endAt.getTime()){ System.out.println("当前时间大于结束时间");}