判斷一個字符串能不能轉化成時間格式


采用SimpleDateFormat類的parse方法進行判斷,如果轉換不成功,就會出現異常,

具體代碼如下:

 1 package com.test01;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 
 6 public class test03 {
 7 
 8     public static void main(String[] args) {
 9         System.out.println(isValidDate("2018/12/12 02:02:12"));
10     }
11     
12      public static boolean isValidDate(String str) {
13          boolean convertSuccess=true;
14          // 指定日期格式為四位年/兩位月份/兩位日期,注意yyyy/MM/dd區分大小寫;
15          SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
16          try {
17                //設置lenient為false. 否則SimpleDateFormat會比較寬松地驗證日期,比如2007/02/29會被接受,並轉換成2007/03/01
18             format.setLenient(false);
19             format.parse(str);
20          } catch (ParseException e) {
21             // e.printStackTrace();
22               // 如果throw java.text.ParseException或者NullPointerException,就說明格式不對
23             convertSuccess=false;
24          } 
25          return convertSuccess;
26      }         
27 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM