介绍
Calendar类是日历类,提供操作日历字段的方法
知识点1:获取Calendar对象的方法
想得到一个Calendar类对象的话,不能采用new对象的方式。因为Calendar类的构造函数被protected修饰符修饰
protected Calendar()
{
this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
sharedZone = true;
}
正确获取Calendar对象的方法是:
Calendar calBegin = Calendar.getInstance();
知识点2:相关日历字段
注意:
(1)AM_PM 返回0表示上午,返回1则表示是下午
(2)国外月份是0~11月,因此需要将得到的月份进行+1操作
知识点3:常用的方法
- public Date getTime() :得到当前日历时间,返回Date类型时间
- public void setTime(Date date) :使用给定的Date设置日历时间
- abstract void add(int field,int amount) :按照日历的规则,给指定字段添加或减少时间量。当amount为负数时代表减少指定的时间量
- public void set(int field, int value):给日历类的指定字段赋值
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
- public int get(int field):返回给定日历字段的值
实际应用
一、获取近一个月每一天日期的数组
static List<String> dateListOfNearlyAMonth = new ArrayList<>();
static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
static Date endDate = null;
static Date startDate = null;
// 根据给出的开始日期和结束日期,得到这段时间内每一天的具体日期
public static List<String> findDates(Date dBegin, Date dEnd){
List<String> lDate = new ArrayList();
lDate.add(format.format(dBegin));
Calendar calBegin = Calendar.getInstance();
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
calEnd.setTime(dEnd);
// 测试此日期是否在指定日期之后
while (dEnd.after(calBegin.getTime()))
{
System.out.println("count: " + count);
calBegin.add(Calendar.DAY_OF_MONTH, 1);
String tempDate = format.format(calBegin.getTime());
lDate.add(tempDate);
}
return lDate;
}
// 获取当前日期,以及一个月前的日期
public static void getDateListOfNearlyAMonth() throws Exception{
String currDate = format.format(new Date());
endDate = format.parse(currDate);
System.out.println("今天日期:" + currDate + ' ' + endDate);
//过去一月
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH,-1);
Date m = c.getTime();
String monDate = format.format(m);
startDate = format.parse(monDate);
System.out.println("过去一个月:" + monDate + " " + startDate);
dateListOfNearlyAMonth = findDates(startDate, endDate);
System.out.println("dateListOfNearlyAMonth len: " + dateListOfNearlyAMonth.size());
}
二、获取过去七天、过去一月、过去三个月、过去一年的日期
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("今天日期:" + format.format(new Date()));
Calendar c = Calendar.getInstance();
//过去七天
c.setTime(new Date());
c.add(Calendar.DATE, -7);
Date d = c.getTime();
String day = format.format(d);
System.out.println("过去七天:"+day);
//过去一月
c.setTime(new Date());
c.add(Calendar.MONTH,-1);
Date m = c.getTime();
String mon = format.format(m);
System.out.println("过去一个月:"+mon);
//过去三个月
c.setTime(new Date());
c.add(Calendar.MONTH,-3);
Date m3 = c.getTime();
String mon3 = format.format(m3);
System.out.println("过去三个月:"+mon3);
//过去一年
c.setTime(new Date());
c.add(Calendar.YEAR,-1);
Date y = c.getTime();
String year = format.format(y);
System.out.println("过去一年:"+year);