java.util.Calendar获取时间区间问题

虽然java8的LocalDate已经出来,但是很多项目以及自己习惯上还是使用Date,这里还是简单介绍一下如何通过java.util.Calendar获取时间区间.

1 通过calendar.getActualMinimum,getActualMaximum获取周,月,年的最大值,最小值

 1     /**
 2      * @Title: getSeasonFrist
 3      * @Description: 获取季度初日期
 4      * @param calendar
 5      * @return
 6      * @throws ParseException
 7      */
 8     public static String getSeasonFrist(Calendar calendar) throws ParseException {
 9         int month = calendar.get(Calendar.MONTH);
10         int season = getSeason(month, 0);
11         calendar.set(Calendar.DAY_OF_MONTH, 0);
12         calendar.set(Calendar.MONTH, season);
13         calendar.add(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
14         return sdf.format(calendar.getTime());
15     }
16 
17     /**
18      * @Title: getSeasonLast
19      * @Description: 获取季度末日期时间
20      * @param calendar
21      * @return
22      * @throws ParseException
23      */
24     public static String getSeasonLast(Calendar calendar) throws ParseException {
25         int month = calendar.get(Calendar.MONTH);
26         int season = getSeason(month, 1);
27         calendar.set(Calendar.MONTH, season);
28         calendar.set(Calendar.DAY_OF_MONTH, -1);
29         calendar.add(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
30         return sdf.format(calendar.getTime());
31     }

问题,因为直接设置月份,除了月份其他信息没有改,会造成获取月份最大值不准确,即当前月是9月,我把月份改成10,但是9月的最大天数是30,所以获取月份最后一天就是:10月30日

方式二:通过获取下月月初减一的方式获取区间最后一天,这种方式可简单有效解决月末日期不准确问题

 1     /**
 2      * @Title: getSeasonFrist
 3      * @Description: 获取季度初日期
 4      * @param calendar
 5      * @return
 6      * @throws ParseException
 7      */
 8     public static String getSeasonFrist(Calendar calendar) throws ParseException {
 9         int month = calendar.get(Calendar.MONTH);
10         int season = getSeason(month, 0);
11         calendar.set(Calendar.MONTH, season);
12         calendar.set(Calendar.DAY_OF_MONTH, 1);
13         return sdf.format(calendar.getTime());
14     }
15 
16     /**
17      * @Title: getSeasonLast
18      * @Description: 获取季度末日期时间
19      * @param calendar
20      * @return
21      * @throws ParseException
22      */
23     public static String getSeasonLast(Calendar calendar) throws ParseException {
24         int month = calendar.get(Calendar.MONTH);
25         int season = getSeason(month, 1);
26         calendar.set(Calendar.MONTH, season + 1);
27         calendar.set(Calendar.DAY_OF_MONTH, 0);
28         return sdf.format(calendar.getTime());
29     }

这里用季度的例子举例,月和年类似;因为calendar没有直接获取季度的方法,季度的区间需要自己定义,其实就是获取当前月,然后自己定义每个月属于哪个季度,并返回季度首尾的月份;

posted @ 2017-10-19 13:22  橙木鱼  阅读(1742)  评论(0编辑  收藏  举报