java校验时间格式 HH:MM

  1. package com;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5.   
  6. /** 
  7.  * @author Gerrard 
  8.  */  
  9. public class CheckTimeHHMM {  
  10.       
  11.     public static void main(String[] args) {  
  12.         boolean flg = checkTime("8:00");  
  13.         boolean flg3 = checkTime("24:00");  
  14.         boolean flg1 = checkTime("8:60");  
  15.         boolean flg2 = checkTime("25:00");  
  16.         boolean flg4 = checkTime("25:0-");  
  17.         boolean flg6 = checkTime("ss:0-");  
  18.         if (flg) {  
  19.             System.out.println("8:00是正确格式");  
  20.         }  
  21.         if (flg3) {  
  22.             System.out.println("24:00是正确格式");  
  23.         }  
  24.         if (!flg1) {  
  25.             System.out.println("8:60不是正确格式");  
  26.         }  
  27.         if (!flg2) {  
  28.             System.out.println("25:00不是正确格式");  
  29.         }  
  30.         if (!flg4) {  
  31.             System.out.println("25:0-不是正确格式");  
  32.         }  
  33.         if (!flg6) {  
  34.             System.out.println("ss:0-不是正确格式");  
  35.         }  
  36.     }  
  37.       
  38.     /** 
  39.      * 校验时间格式(仅格式) 
  40.      */  
  41.     public static boolean checkHHMM(String time) {  
  42.         SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");  
  43.          try {  
  44.              @SuppressWarnings("unused")  
  45.             Date t = dateFormat.parse(time);  
  46.          }  
  47.          catch (Exception ex) {  
  48.              return false;  
  49.          }  
  50.         return true;  
  51.     }  
  52.       
  53.     /** 
  54.      * 校验时间格式HH:MM(精确) 
  55.      */  
  56.     public static boolean checkTime(String time) {  
  57.         if (checkHHMM(time)) {  
  58.             String[] temp = time.split(":");  
  59.             if ((temp[0].length() == 2 || temp[0].length() == 1) && temp[1].length() == 2) {  
  60.                 int h,m;  
  61.                 try {  
  62.                     h = Integer.parseInt(temp[0]);  
  63.                     m = Integer.parseInt(temp[1]);  
  64.                 } catch (NumberFormatException e) {  
  65.                     return false;  
  66.                 }     
  67.                 if (h >= 0 && h <= 24 && m <= 60 && m >= 0) {  
  68.                     return true;  
  69.                 }  
  70.             }  
  71.         }  
  72.         return false;  
  73.     }  
  74.   
  75. }
原文地址:https://www.cnblogs.com/kabi/p/6125156.html