1、Java(service方法)端获取当前时间的前12个小时:
public Object getSearchName(HttpServletRequest request){
JSONArray arr = new JSONArray();
JSONObject obj = new JSONObject();
JSONObject objFirst = new JSONObject();
objFirst.put("itemname", "--请选择--");
objFirst.put("itemvalue", "");
arr.add(objFirst);
//获取当前时间的24个小时数
for(int i=0;i<24;i++){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY)-i);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//System.out.println(i+"小时前时间为:"+df.format(calendar.getTime()));
//System.out.println("当前时间:"+df.format(new Date()));
obj.put("itemname",df.format(calendar.getTime()));
obj.put("itemvalue", df.format(calendar.getTime()));
arr.add(obj);
}
return arr.toString();
}
2、Java方法写在一个静态类里,可以直接通过方法名调用:String searchbefore = DateUtil.getDate(searchtime, -1);
/**
*
* @Title:
* @Description:获取提前或延后的日期,格式为yyyy-MM-dd HH:mm
* @return String
* @Version:1.1.0
*/
public static String getDate(String dateStr, int hour) {
try {
SimpleDateFormat format = new SimpleDateFormat(CURRENT_YEAR_PATTERN3);
java.util.Date date = format.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hour);
return format.format(cal.getTime());
} catch (Exception e) {
return "";
}
}