java get two days difference in time

Through a comparison between the start time and the end time, the start time cannot be greater than the current time, and the end time cannot be later than the current time.
If the current system time is earlier than the start time, it will directly return to 0 days. If the end time is later than the current system time, the system time will be used as the end time.

public static int dateDay(String startTime,String endTime){
    
    
        //设置转换的日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long betweenDate;
        try {
    
    
            //开始时间
            Date startDate = sdf.parse(startTime);
            //结束时间
            Date endDate = sdf.parse(endTime);
            Date newDate = new Date();
            if (startDate.after(newDate)) {
    
    
                //开始时间比当前时间还大,则返回0天
                return 0;
            }
            if (endDate.before(newDate)){
    
    
                //结束时间在系统时间前获得结束开始时间到结束时间相差的天数 betweenDate
                betweenDate = (endDate.getTime() - startDate.getTime())/(60*60*24*1000);
            }else {
    
    
                //结束时间在系统时间后获得结束开始时间到结束时间相差的天数 betweenDate
                betweenDate = (newDate.getTime() - startDate.getTime())/(60*60*24*1000);
            }
            //打印控制台相差的天数
            //System.out.println(betweenDate);
            return (int) betweenDate ;
        } catch (ParseException e) {
    
    
            return 0;
        }
    }


Guess you like

Origin blog.csdn.net/zhongzih/article/details/105292527