Calendar类常用需求方法

时间:2022-07-23 14:36:36

经常处理一些日期相关的信息,Calendar类是处理日期的常用类,写下几个方法,不用重复造*了。

1.求上一天,下一天的日期

Date now = new Date();
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(Calendar.DAY_OF_MONTH, -1);  // 下一天,上一天-1改为1
Date yesterday = c.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
System.out.println(sdf.format(yesterday));

2.给定开始时间和结束时间,输出中间每一天

Date now = new Date();
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String begin = "20161201";
String end = "20170210";
try {
Date begin_date = sdf.parse(begin);
Date end_date = sdf.parse(end);

List<Date> lDate = new ArrayList<Date>();
lDate.add(begin_date);
Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calBegin.setTime(begin_date);
Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calEnd.setTime(end_date);
// 测试此日期是否在指定日期之后
while (end_date.after(calBegin.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
calBegin.add(Calendar.DAY_OF_MONTH, 1);
lDate.add(calBegin.getTime());
}

for (Date date : lDate) {
String format = sdf.format(date);
System.out.println(format);
}

3.compareTo()方法,比较两个Calendar的日期谁在前谁在后,在之前的话为-1,相同为0,在之后为1

4.Calendar类的before和after方法,参数都为Calendar才能正确比较