时间工具类,根据本月时间获取前面几个月的时间并格式化日期

最近项目有个需求,统计某个字段每月的总量并统计出增量。
问题在于:每个月的总量不好查,没法根据某个字段来区分该条数据属于哪个月的数据。所以最后只能查根据日期来查该日期之前的所有数据。

写了个工具了,传入当前时间(如:2019-11)和所需前推的月份数量(如:6);返回dataArr[]字符串数组。
直接上代码:


```java
public static Date getDateFromDateJudice(Date date , Integer length, int type){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(type, calendar.get(type)+length);
        return calendar.getTime();
    }
    /**
     * 获取指定日期前length天数集合
     * @param dateKey  当前时间月份
     * @param length 月份,向前推几个月
     * @return
     */
    public static String[] getDateListBeforeLength(String dateKey, Integer length) throws ParseException {
        String[] dateArr = new String[length];
        dateArr[0] = dateKey;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date beginDate = sdf.parse(dateKey);
        for (Integer i = 1; i < length; i++) {
            Date endDate = getDateFromDateJudice(beginDate, 0 - i,Calendar.MONTH);
            String endKey = sdf.format(endDate);
            dateArr[i] = endKey;
        }
        return dateArr;
    }

获取系统时间为:

系统时间

返回字符串数组为:

返回字符串数组

可以跨年计算哦~

记录在此,方便下次使用。

转载需要注明出处哦~

猜你喜欢

转载自blog.csdn.net/weixin_43829443/article/details/103147285
今日推荐