Java判断某时间是否在一个时间段

用于限时循环的活动:

public class TestDate
{

    public static void main(String[] args)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();

        String strDate = sdf.format(date);

        // 截取当前时间时分
        int strDateH = Integer.parseInt(strDate.substring(11, 13));
        int strDateM = Integer.parseInt(strDate.substring(14, 16));
        String curTime = strDateH+":"+strDateM;
        System.out.println(curTime);

        String sourceTime ="09:00-23:00";
        boolean inTime = isInTime(sourceTime, curTime);
        System.out.println(inTime);
        
    }
    
    /** 
     * 判断某一时间是否在一个区间内 
     *  
     * @param sourceTime 
     *            时间区间,半闭合,如[10:00-20:00) 
     * @param curTime 
     *            需要判断的时间 如10:00 
     * @return  
     * @throws IllegalArgumentException 
     */  
    public static boolean isInTime(String sourceTime, String curTime) {  
        if (sourceTime == null || !sourceTime.contains("-") || !sourceTime.contains(":")) {  
            throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);  
        }  
        if (curTime == null || !curTime.contains(":")) {  
            throw new IllegalArgumentException("Illegal Argument arg:" + curTime);  
        }  
        String[] args = sourceTime.split("-");  
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");  
        try {  
            long now = sdf.parse(curTime).getTime();  
            long start = sdf.parse(args[0]).getTime();  
            long end = sdf.parse(args[1]).getTime();  
            if (args[1].equals("00:00")) {  
                args[1] = "24:00";  
            }  
            if (end < start) {  
                if (now >= end && now < start) {  
                    return false;  
                } else {  
                    return true;  
                }  
            }   
            else {  
                if (now >= start && now < end) {  
                    return true;  
                } else {  
                    return false;  
                }  
            }  
        } catch (ParseException e) {  
            e.printStackTrace();  
            throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);  
        }  
      
    } 

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这次连续多天的奔波劳累之后,从外面回到家中,母亲见我的第一句话就是“你难道在外面没有吃饱饭,血色都不如以前了”。 ...
    小杨林阅读 215评论 0 0
  • 我想说的话很多 只是你不想听 说 背对背都在哭泣 认真听的人会以为都是寂寞 哭着 捡一颗石子投向那片水 石拍出水花...
    脑袋里有病灶阅读 266评论 2 4