本文共 2998 字,大约阅读时间需要 9 分钟。
Calendar类是日历类,提供操作日历字段的方法
想得到一个Calendar类对象的话,不能采用new对象的方式。因为Calendar类的构造函数被protected修饰符修饰
protected Calendar() { this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT)); sharedZone = true; }
正确获取Calendar对象的方法是:
Calendar calBegin = Calendar.getInstance();
Calendar calendar = Calendar.getInstance();calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
一、获取近一个月每一天日期的数组
static ListdateListOfNearlyAMonth = new ArrayList<>();static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");static Date endDate = null;static Date startDate = null;// 根据给出的开始日期和结束日期,得到这段时间内每一天的具体日期public static List findDates(Date dBegin, Date dEnd){ List 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);
转载地址:http://vhtii.baihongyu.com/