Calendar类常用需求方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Calendar类常用需求方法相关的知识,希望对你有一定的参考价值。

经常处理一些日期相关的信息,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才能正确比较

以上是关于Calendar类常用需求方法的主要内容,如果未能解决你的问题,请参考以下文章

Calendar日期类详解SimpleDateFormat时区Date夏令时常用方法,日期差获取当前时间

阶段1 语言基础+高级_1-3-Java语言高级_03-常用API第二部分_第3节 Calendar类_2_Calendar类的常用成员方法

Calendar类

Java_常用类14_Calendar类

Calendar是日历类

JAVA07_Calendar的概述Date的互转常量字段常用方法