Java 获取近七天、近六个月(包含今天,本月)

Java 获取近七天、近六个月(包含今天,本月),第1张

Java 获取近七天、近六个月(包含今天,本月) 获取近七天
        List dateList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 7; i++) {
            Date date = DateUtils.addDays(new Date(), -i);
            String formatDate = sdf.format(date);
            dateList.add(formatDate);
        }
 
 获取近六个月

1.不带年份

    List resultList = new ArrayList();
        Calendar cal = Calendar.getInstance();
        //近六个月
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1); //要先+1,才能把本月的算进去
        for(int i=0; i<6; i++){
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1); //逐次往前推1个月
            resultList.add( (cal.get(Calendar.MONTH)+1 < 10 ? "0" 
                    + (cal.get(Calendar.MONTH)+1) : String.valueOf((cal.get(Calendar.MONTH)+1))));
        }

 2.带年份的

    List resultList = new ArrayList();
        Calendar cal = Calendar.getInstance();
        //近六个月
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1); //要先+1,才能把本月的算进去
        for(int i=0; i<6; i++){
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1); //逐次往前推1个月
            resultList.add(String.valueOf(cal.get(Calendar.YEAR)) 
                    +"-"+ (cal.get(Calendar.MONTH)+1 < 10 ? "0" + 
                        (cal.get(Calendar.MONTH)+1) : (cal.get(Calendar.MONTH)+1)));
        }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5608185.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存