判断给出的时间是否在当前时间过去的一个小时内
- 工作中遇到的问题,需要查询数据库中的一些数据,这些数据要满足:查询时过去的一个小时内数据有多少条,做了如下工具类来判断查到的数据是否符合条件,有问题欢迎指出!
public class DateUtils {
public static void main(String[] args) {
String time = "15:30:08";
if(isInAnHour(time)) {
System.out.println("Yes!");
}else {
System.out.println("No!");
}
}
public static boolean isInAnHour(String tempTime) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, (time.get(Calendar.HOUR_OF_DAY) - 1));
String aHourAgo = sdf.format(time.getTime());
Date now = null;
Date ago = null;
Date temp = null;
try {
now = sdf.parse(getSysTime("HH:mm:ss"));
ago = sdf.parse(aHourAgo);
temp = sdf.parse(tempTime);
} catch (ParseException e) {
e.printStackTrace();
}
return ((temp.getTime() - ago.getTime() > 0) && (now.getTime() - temp.getTime() > 0));
}
public static String getSysTime(String format) {
Date date = new Date();
if (format == null || format.equals("")) {
format = "HHmmss";
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(date);
}
}