Given the start time and end time, complete the interval date and calculate the time difference

Given the start time and end time, complete the interval date and calculate the time difference.
Given a start time and end time, calculate all dates between the two times, and calculate how long the two times differ.
Look directly at the code:

public static List<String> getDate(String startTime,String endTime){
    
    
        List<String> date = new ArrayList<>();

        try {
    
    
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            //开始时间
            Date start = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
            //结束时间
            Date end = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
            //仅支持查看90天的数据
            long time = (end.getTime() - start.getTime())/(1000 * 60 * 60 * 24) + 1;
            Assert.isTrue(time <= 90,"包含开始时间,结束时间,仅支持查看90天数据,当前查询天数:" + time + "天");
            Calendar calendar = Calendar.getInstance();
            //设置起始时间
            calendar.setTime(start);
            date.add(startTime);
            while (calendar.getTime().before(end)){
    
    
            	//时间加一天
                calendar.add(Calendar.DATE,1);
                String format1 = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
                date.add(format1);
            }
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        return date;
    }

The idea is very simple: Given an initial time, judge whether the initial time is less than the end time, if less than, add 1 to the number of days in turn, and store it in the collection, until the start time is equal to the end time to end the cycle, just return to the collection.

The above content is for reference only, and should be adjusted according to your own business needs.

Guess you like

Origin blog.csdn.net/weixin_51114236/article/details/128207818