java 在现有时间,年、月、日上加时间
第一种方式
Date date = new Date();
System.out.println("data1 = "+date.toLocaleString());
date.setHours(new Date().getHours()+3);
System.out.println("date2 = "+date.toLocaleString());
date.setYear(new Date().getYear()+2);
System.out.println("date3 = "+date.toLocaleString());
运行结果:
data1 = 2018-10-10 16:22:44
date2 = 2018-10-10 19:22:44
date3 = 2020-10-10 19:22:44
第二种方式
String d = "2018-10-10 16:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
try {
cal.setTime(sdf.parse(d));
} catch (ParseException e) {
e.printStackTrace();
}
//+3小时
cal.add(Calendar.HOUR_OF_DAY, 3);
System.out.println(sdf.format(cal.getTime()));
运行结果:
2018-10-10 19:00:00