计算指定日期以后间隔指定天数的所有日期

计算间隔的天数:


    /**
     * 计算两个日期之间相差的天数
     *
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate) {
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
    
    
            smdate = sdf.parse(sdf.format(smdate));
            bdate = sdf.parse(sdf.format(bdate));
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }


    /**
     * 字符串的日期格式的计算
     *
     * @param smdate
     * @param bdate
     * @return
     * @throws ParseException
     */
    public static int daysBetween(String smdate, String bdate) {
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        long between_days = 0;
        try {
    
    
            cal.setTime(sdf.parse(smdate));
            long time1 = cal.getTimeInMillis();
            cal.setTime(sdf.parse(bdate));
            long time2 = cal.getTimeInMillis();
            between_days = (time2 - time1) / (1000 * 3600 * 24);
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        return Integer.parseInt(String.valueOf(between_days));
    }

获取所有的日期

    public static List<LocalDate> getDateList(String startDateTmp, int diffDays) {
    
    
        LocalDate startDate = LocalDate.parse(startDateTmp);
        LocalDate endDate = startDate.plusDays(diffDays);
        long numOfDays = ChronoUnit.DAYS.between(startDate, endDate);
        List<LocalDate> listOfDates2 = LongStream.range(0, numOfDays)
                .mapToObj(startDate::plusDays)
                .collect(Collectors.toList());
        listOfDates2.forEach(item->{
    
    
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            System.out.println(dateTimeFormatter.format(item));
        });
        return listOfDates2;
    }

Guess you like

Origin blog.csdn.net/hs_shengxiaguangnian/article/details/120511572