Java判斷某時(shí)間是否在一個(gè)時(shí)間段

用于限時(shí)循環(huán)的活動:

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);

        // 截取當(dāng)前時(shí)間時(shí)分
        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);
        
    }
    
    /** 
     * 判斷某一時(shí)間是否在一個(gè)區(qū)間內(nèi) 
     *  
     * @param sourceTime 
     *            時(shí)間區(qū)間,半閉合,如[10:00-20:00) 
     * @param curTime 
     *            需要判斷的時(shí)間 如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);  
        }  
      
    } 

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 這次連續(xù)多天的奔波勞累之后,從外面回到家中,母親見我的第一句話就是“你難道在外面沒有吃飽飯,血色都不如以前了”。 ...
    小楊林閱讀 271評論 0 0
  • 我想說的話很多 只是你不想聽 說 背對背都在哭泣 認(rèn)真聽的人會以為都是寂寞 哭著 撿一顆石子投向那片水 石拍出水花...
    腦袋里有病灶閱讀 275評論 2 4

友情鏈接更多精彩內(nèi)容