Java 8 之前日期时间写法
/**
* 获取当前时间小时整点时间
*
* @param
* @return
*/
public static Date getCurrentHourTime() {
return getHourTime(new Date(), 0, "=");
}
/**
* 获取指定时间上n个小时整点时间
*
* @param date
* @return
*/
public static Date getLastHourTime(Date date, int n) {
return getHourTime(date, n, "-");
}
/**
* 获取指定时间下n个小时整点时间
*
* @param date
* @return
*/
public static Date getNextHourTime(Date date, int n) {
return getHourTime(date, n, "+");
}
/**
* 获取指定时间n个小时整点时间
*
* @param date
* @return
*/
public static Date getHourTime(Date date, int n, String direction) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
ca.set(Calendar.MINUTE, 0);
ca.set(Calendar.SECOND, 0);
switch (direction) {
case "+":
ca.set(Calendar.HOUR_OF_DAY, ca.get(Calendar.HOUR_OF_DAY) + n);
break;
case "-":
ca.set(Calendar.HOUR_OF_DAY, ca.get(Calendar.HOUR_OF_DAY) - n);
break;
case "=":
ca.set(Calendar.HOUR_OF_DAY, ca.get(Calendar.HOUR_OF_DAY));
break;
default:
ca.set(Calendar.HOUR_OF_DAY, ca.get(Calendar.HOUR_OF_DAY));
}
date = ca.getTime();
return date;
}
Java 8 新的日期时间类 写法
/**
* 获取当前时间上iHour个小时整点时间
*
* @param iHour 小时数
* @return
*/
public static Date getLastHourTime(Integer iHour) {
LocalDateTime localDateTime = LocalDateTime.now().minusHours(iHour).toLocalDate().atTime(LocalDateTime.now().minusHours(iHour).getHour(), 0, 0);
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
/**
* 获取当前时间的整点时间向前推iSecond秒
*
* @param iSecond 秒数
* @return
*/
public static Date getLastSecondByCurrHourTime(Integer iSecond) {
LocalDateTime localDateTime = LocalDateTime.now().toLocalDate().atTime(LocalDateTime.now().getHour(), 0, 0).minusSeconds(iSecond);
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}