Get the date within the time period (available for personal testing)

Sometimes we need to generate data over a period of time.
If you run data day by day, congratulations, you understand~~ The following is a tool class for traversing dates. When calling, just pass the start time and end time.

/**
     * 获取时间段内的时间方法
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> dateSplit(String startTime, String endTime) {
    
    
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        List<String> timeList = new ArrayList<>();
        try {
    
    
            // 起始日期
            Date d1 = sdf.parse(startTime);
            // 结束日期
            Date d2 = sdf.parse(endTime);
            Date tmp = d1;
            calendar.setTime(d1);
            while (tmp.getTime() < d2.getTime()) {
    
    
                timeList.add(sdf.format(calendar.getTime()));
                tmp = calendar.getTime();
                // 天数加上1
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        return timeList;
    }

Let's test it next

    public static void main(String[] args) {
    
    
        List<String> timeList = dateSplit("2023-02-20", "2023-02-28");
        for (String time : timeList) {
    
    
//            此处可以调用业务
            System.out.println(time);
      }
   }

Let’s take a look at the results

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-HDLfJpxw-1677508422228) (attachment:0192c751811ff03b3ae8847e977d3e7e)]

Okay, take it and use it, friends~~

Guess you like

Origin blog.csdn.net/xiangyuWA/article/details/129251728