java中如何对比时间的前后

来源:互联网 发布:市政工程预算软件 编辑:程序博客网 时间:2024/04/29 09:12

java中如何对比时间的前后

开发中日期使用很频繁,免不了要判断时间的前后顺序,java中该如何做呢?

  • 这部分没什么好讲的,直接上Demo
    /**     * @description 判断某个时间点是否在某个时间范围内     * @param date 时间点     * @param startDate 开始时间     * @param endDate 结束时间     * @return 在:true; 不在:false     *     * @author ZF     * @date 2017年10月12日11:51:58     */    public static boolean isBetweenTwoDate(Date date, Date startDate, Date endDate) {        if (startDate.before(date) && endDate.after(date)) {            return true;        }        return false;    }    /**     * @description 判断某个时间点是否在某个时间范围内     * @param nowTime 时间点     * @param beginTime 时间范围头     * @param endTime 时间范围尾     * @return 在:true; 不在:false     *     * @author ZF     * @date 2017年8月23日16:07:13     */    public static boolean containCalendar(Date nowTime, Date beginTime, Date endTime) {        Calendar now = Calendar.getInstance();        now.setTime(nowTime);        Calendar begin = Calendar.getInstance();        begin.setTime(beginTime);        Calendar end = Calendar.getInstance();        end.setTime(endTime);        if (now.after(begin) && now.before(end)) {            return true;        } else {            return false;        }    }    public static void main(String[] args) throws ParseException {        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");   // 这里的时间格式任意        Date begin = format.parse("2010/01/09 00:00:00");        Date end = format.parse("2010/01/11 07:00:00");        Date now = format.parse("2010/01/10 00:00:00");        System.out.println(isBetweenTwoDate(now, begin, end));        System.out.println(containCalendar(now, begin, end));    }

代码中的时间格式不限,就是说无论你是什么时间格式,只要三个时间格式一致,就可以比对出来。

  • 另外,要注意的是时间范围比对不包头,不包尾。
  • 即,不是 [ )、 不是 ( ]、 也不是 [ ]
  • 是( )
原创粉丝点击