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