获得已过月份起始和结束时间及当月的起始时间到当前时间

需求解析:

获得已过月份起始和结束时间及当月的起始时间到当前时间,当前时间是2018-09-08 15:35:00,即9月份:要得到

一月份:"2018-01-01 00:00:00":"2018-01-31 23:59:59",

二月份:"2018-02-01 00:00:00":"2018-02-28 23:59:59"

...

九月份:"2018-09-01 00:00:00":"2018-09-08 15:35:00"

代码如下:

  public static String[] getEveryMonth(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        Map<String, Object> params = Maps.newHashMap();
        String endMonth = "";
        //分别获取当前日期的年月日
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        String[] startAndEndMonth = new String[month+1];

        //获取到统计截止日期(当前时间)
        String endTime = formatter.format(calendar.getTime());
        //得到当月的开始时间
        calendar.set(year, month, 1, 0, 0, 0);
        String startMonth = formatter.format(calendar.getTime());
        params.put(startMonth, endTime);
        startAndEndMonth[month] = JSON.toJSONString(params);
        for (int i = 0; i < month; i++) {
            calendar.clear();
            //获取当月前的月的起始时间和结束时间
            calendar.set(year, i, 1, 0, 0, 0);
            startMonth = formatter.format(calendar.getTime());
            calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(
                    Calendar.DAY_OF_MONTH));
            calendar.set(year, i, calendar.get(Calendar.DATE), 23, 59, 59);
            endMonth = formatter.format(calendar.getTime());
            params.clear();
            params.put(startMonth, endMonth);
            startAndEndMonth[i] = JSON.toJSONString(params);
        }
        return startAndEndMonth;
    }

 执行方法:

  public static void main(String[] args) {
        String[] strs = getEveryMonth();
        for (String str : strs) {
            Map<String, Object> params = JSON.parseObject(str);
            System.err.println(params);
        }
    }

执行结果:

 

posted @ 2018-09-08 15:50  nihao小树苗  阅读(1316)  评论(0编辑  收藏  举报