在项目中,会经常需要获取过去几天,几月,几年前的时间,所以这里采用Calendar中的add方法获取。
源码:Adds or subtracts the specified amount of time to the given calendar field,based on the calendar's rules. For example, to subtract 5 days fromthe current time of the calendar, you can achieve it by calling:
意思就是根据日历规则,向给定日历字段添加或减去指定的时间。第一个参数为当前的时间(时分秒,年月日),第二个参数是需要加减的时间。
add:
例如:我需要获取当前七天前的时间:param1 当前日期,param2 七天前日期,采用负数;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
//过去七天
c.setTime(new Date());
c.add(Calendar.DATE, - 7);
Date d = c.getTime();
String day = format.format(d);
LOGGER.info("当前时间的前七天时间为:" + day);
运行结果:
set:
主要是设置自己需要的时间,没有具体用过。不多描述
Calendar c = Calendar.getInstance();
// 获取月
int year = c.get(Calendar.YEAR);
// 获取月
int month = c.get(Calendar.MONTH);
// 获取日
c.set(2018, 01, 12);
// 获取月
year = c.get(Calendar.YEAR);
// 获取月
month = c.get(Calendar.MONTH);
// 获取日
date = c.get(Calendar.DATE);
System.out.println(year + "年" + (month + 1) + "月" + date + "日");
运行结果: