Home  >  Article  >  Java  >  How to determine whether a string is in date format in java

How to determine whether a string is in date format in java

尚
Original
2019-11-23 11:02:505588browse

How to determine whether a string is in date format in java

java判断指定字符串是否日期格式:

/**
	 * 通过正则表达式检查是否符合时间格式
	 */
	@SuppressWarnings("unused")	private boolean checkTimeFormat(String validateDate) {		boolean flag = false;		if(StringUtils.isNotEmpty(validateDate)){
			String datePattern1 = "\\d{4}-\\d{2}-\\d{2}";  
			String datePattern2 = "^((\\d{2}(([02468][048])|([13579][26]))" 
	              + "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|" 
	              + "(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?" 
	              + "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?(" 
	              + "(((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?" 
	              + "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";  			
			if (validateDate != null) {  
		          Pattern pattern = Pattern.compile(datePattern1);  
		          Matcher match = pattern.matcher(validateDate);  
		          if (match.matches()) {  
		              pattern = Pattern.compile(datePattern2);  
		              match = pattern.matcher(validateDate);  
		              
		             // return match.matches();  
		              return flag = true;
		          }  
		          else {  
		              return flag;  
		          }  
		      } 
			
		}		
		return flag;
	}

Java 正则表达式

正则表达式定义了字符串的模式。

正则表达式可以用来搜索、编辑或处理文本。

正则表达式并不仅限于某一种语言,但是在每种语言中有细微的差别。

正则表达式实例

一个字符串其实就是一个简单的正则表达式,例如 Hello World 正则表达式匹配 "Hello World" 字符串。

.(点号)也是一个正则表达式,它匹配任何一个字符如:"a" 或 "1"。

matches() 方法用于检测字符串是否匹配给定的正则表达式。在字符串匹配给定的正则表达式时,返回 true。

更多java知识请关注java基础教程

The above is the detailed content of How to determine whether a string is in date format in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn