Java时间判断:判断一个时间是否在一个时间段内

来源:互联网 发布:光伏电站数据采集器 编辑:程序博客网 时间:2024/05/16 10:45

Java时间判断:判断一个时间是否在一个时间段内

    博客分类: 
  • JavaSE
时间date时间段JavaJava判断时间 

需求:当时间在凌晨0点至0点5分之间程序不执行。

也就是实现判断当前时间点是否在00:00:00至00:05:00之间

方法:

Java代码  收藏代码
  1. /** 
  2.  * 判断时间是否在时间段内 
  3.  *  
  4.  * @param date 
  5.  *            当前时间 yyyy-MM-dd HH:mm:ss 
  6.  * @param strDateBegin 
  7.  *            开始时间 00:00:00 
  8.  * @param strDateEnd 
  9.  *            结束时间 00:05:00 
  10.  * @return 
  11.  */  
  12. public static boolean isInDate(Date date, String strDateBegin,  
  13.         String strDateEnd) {  
  14.     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  15.     String strDate = sdf.format(date);  
  16.     // 截取当前时间时分秒  
  17.     int strDateH = Integer.parseInt(strDate.substring(1113));  
  18.     int strDateM = Integer.parseInt(strDate.substring(1416));  
  19.     int strDateS = Integer.parseInt(strDate.substring(1719));  
  20.     // 截取开始时间时分秒  
  21.     int strDateBeginH = Integer.parseInt(strDateBegin.substring(02));  
  22.     int strDateBeginM = Integer.parseInt(strDateBegin.substring(35));  
  23.     int strDateBeginS = Integer.parseInt(strDateBegin.substring(68));  
  24.     // 截取结束时间时分秒  
  25.     int strDateEndH = Integer.parseInt(strDateEnd.substring(02));  
  26.     int strDateEndM = Integer.parseInt(strDateEnd.substring(35));  
  27.     int strDateEndS = Integer.parseInt(strDateEnd.substring(68));  
  28.     if ((strDateH >= strDateBeginH && strDateH <= strDateEndH)) {  
  29.         // 当前时间小时数在开始时间和结束时间小时数之间  
  30.         if (strDateH > strDateBeginH && strDateH < strDateEndH) {  
  31.             return true;  
  32.             // 当前时间小时数等于开始时间小时数,分钟数在开始和结束之间  
  33.         } else if (strDateH == strDateBeginH && strDateM >= strDateBeginM  
  34.                 && strDateM <= strDateEndM) {  
  35.             return true;  
  36.             // 当前时间小时数等于开始时间小时数,分钟数等于开始时间分钟数,秒数在开始和结束之间  
  37.         } else if (strDateH == strDateBeginH && strDateM == strDateBeginM  
  38.                 && strDateS >= strDateBeginS && strDateS <= strDateEndS) {  
  39.             return true;  
  40.         }  
  41.         // 当前时间小时数大等于开始时间小时数,等于结束时间小时数,分钟数小等于结束时间分钟数  
  42.         else if (strDateH >= strDateBeginH && strDateH == strDateEndH  
  43.                 && strDateM <= strDateEndM) {  
  44.             return true;  
  45.             // 当前时间小时数大等于开始时间小时数,等于结束时间小时数,分钟数等于结束时间分钟数,秒数小等于结束时间秒数  
  46.         } else if (strDateH >= strDateBeginH && strDateH == strDateEndH  
  47.                 && strDateM == strDateEndM && strDateS <= strDateEndS) {  
  48.             return true;  
  49.         } else {  
  50.             return false;  
  51.         }  
  52.     } else {  
  53.         return false;  
  54.     }  
  55. }  
0 0