设置一个方法在一个时间段内不可以调用

//在时间段08:00:00——17:00:00不可以调用
    public static boolean checkPeriod() throws Exception{
        //现在时间
        Calendar calendar = Calendar.getInstance();
        Date nowDate = calendar.getTime();
        //截取日期,为了拼每天的时间段
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = org.apache.commons.lang3.StringUtils.substringBefore(fmt.format(nowDate)," ");
        //每天的八点开始,九个小时内不可以调用方法
        Calendar begin = Calendar.getInstance();
        Date startTime = fmt.parse(dateStr + " 08:00:00");
        begin.setTime(startTime);
        Date beginDate = begin.getTime();

        Calendar end = Calendar.getInstance();
        end.setTime(startTime);
        end.add(Calendar.HOUR_OF_DAY, 9);    //
        Date endDate = end.getTime();
        if (nowDate.after(beginDate) && nowDate.before(endDate)) {
            //在非法时间段内
            return true;
        } else {
            return false;
        }
    }

最主要的是要记录思维的转变。一开始我一直纠结于在在17:00:00到次日08:00:00之间可以调用,这就判断起来有些复杂了。后来突然意识到我只要判断在哪个时间段内不可以调用就行了啊,08:00:00-17:00:00,不涉及跨天,很好判断

猜你喜欢

转载自blog.csdn.net/u010321349/article/details/86540639