背景
在数据查询中,我们经常需要查询某段时间内的数据,而前端传入参数一般来说是不会指定小时,分钟,秒,甚至毫秒级别的,所以就需要后端进行时间处理;例如:查询2020-02-17 - 2020-02-19 的数据;
方案1
// 返回时间格式如:2020-02-17 00:00:00
public static String getStartOfDay(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}
// 返回时间格式如:2020-02-19 23:59:59
public static String getEndOfDay(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}
// 获取30天以前的时间,同样是比较常用的
public static String getThirtyDaysAgo(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.add(calendar.DATE, -30);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}
方案2
在java8中有更为简洁的代码。
// 获得某天最大时间 2020-02-19 23:59:59
public static Date getEndOfDay(Date date) {
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());;
LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
}
// 获得某天最小时间 2020-02-17 00:00:00
public static Date getStartOfDay(Date date) {
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
}
总结
在查询数据的sql中,通常使用的是字符串,所以一般在处理时间的函数中设定返回值为字符串类型即可;