java中使用Calendar获取指定日期前n个小时的时间日期

public static void main(String[] args) {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String  now = sdf.format(new Date());
  Date beforeHour = beforeHourToNowDate(now ,6);
  System.out.println("1.1 ==="+ sdf.format(beforeHour));
  System.out.println("1.2 ==="+ sdf.format(new Date()));
}

public static Date beforeHourToNowDate(String date ,int hours) {
  Calendar c = Calendar.getInstance();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  try{
    c.setTime(sdf.parse(date));
    c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) - hours);
  }catch (Exception e){
    e.printStackTrace();
  }
  System.out.println("1.3 ==="+ date);
  System.out.println("1.4 ==="+ sdf.format(c.getTime()));
  return c.getTime();
}

你可能感兴趣的:(java中使用Calendar获取指定日期前n个小时的时间日期)