java校验时间格式 HH:MM


  • package com;  
  •   
  • import java.text.SimpleDateFormat;  
  • import java.util.Date;  
  •   
  • /** 
  •  * @author Gerrard 
  •  */  
  • public class CheckTimeHHMM {  
  •       
  •     public static void main(String[] args) {  
  •         boolean flg = checkTime("8:00");  
  •         boolean flg3 = checkTime("24:00");  
  •         boolean flg1 = checkTime("8:60");  
  •         boolean flg2 = checkTime("25:00");  
  •         boolean flg4 = checkTime("25:0-");  
  •         boolean flg6 = checkTime("ss:0-");  
  •         if (flg) {  
  •             System.out.println("8:00是正确格式");  
  •         }  
  •         if (flg3) {  
  •             System.out.println("24:00是正确格式");  
  •         }  
  •         if (!flg1) {  
  •             System.out.println("8:60不是正确格式");  
  •         }  
  •         if (!flg2) {  
  •             System.out.println("25:00不是正确格式");  
  •         }  
  •         if (!flg4) {  
  •             System.out.println("25:0-不是正确格式");  
  •         }  
  •         if (!flg6) {  
  •             System.out.println("ss:0-不是正确格式");  
  •         }  
  •     }  
  •       
  •     /** 
  •      * 校验时间格式(仅格式) 
  •      */  
  •     public static boolean checkHHMM(String time) {  
  •         SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");  
  •          try {  
  •              @SuppressWarnings("unused")  
  •             Date t = dateFormat.parse(time);  
  •          }  
  •          catch (Exception ex) {  
  •              return false;  
  •          }  
  •         return true;  
  •     }  
  •       
  •     /** 
  •      * 校验时间格式HH:MM(精确) 
  •      */  
  •     public static boolean checkTime(String time) {  
  •         if (checkHHMM(time)) {  
  •             String[] temp = time.split(":");  
  •             if ((temp[0].length() == 2 || temp[0].length() == 1) && temp[1].length() == 2) {  
  •                 int h,m;  
  •                 try {  
  •                     h = Integer.parseInt(temp[0]);  
  •                     m = Integer.parseInt(temp[1]);  
  •                 } catch (NumberFormatException e) {  
  •                     return false;  
  •                 }     
  •                 if (h >= 0 && h <= 24 && m <= 60 && m >= 0) {  
  •                     return true;  
  •                 }  
  •             }  
  •         }  
  •         return false;  
  •     }  
  •   
  • }

  • 免责声明!

    本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



     
    粤ICP备18138465号  © 2018-2025 CODEPRJ.COM