Home > Java > JavaBase > body text

Java determines whether the date is legal

Release: 2019-12-27 10:00:24
Original
3896 people have browsed it

Java determines whether the date is legal

In Java, SimpleDateFormat is a concrete class that formats and parses dates in a locale-dependent manner. It allows formatting (date -> text), parsing (text -> date) and normalization, so judging whether a date is legal is also based on this.

import java.text.SimpleDateFormat;
 
class Main {
	public static void main(String[] args) {
		String str1="2000-1-1";
		String str2="2000-1-32";
		System.out.println(check(str1));
		System.out.println(check(str2));
	}
	static boolean check (String str) {
		SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");//括号内为日期格式,y代表年份,M代表年份中的月份(为避免与小时中的分钟数m冲突,此处用M),d代表月份中的天数
		try {
			sd.setLenient(false);//此处指定日期/时间解析是否不严格,在true是不严格,false时为严格
			sd.parse(str);//从给定字符串的开始解析文本,以生成一个日期
		}
		catch (Exception e) {
			return false;
		}
		return true;
	}
}
Copy after login

In java, you can first use SimpleDateFormat to specify the date format, and then use the setLenien(false) method to strictly parse the date, and determine whether the date is legal by checking whether an exception is thrown.

setLenien:

SimpleDateFormat.setLenient(true): The default value is true, the date is not strictly parsed and will be automatically calculated.

SimpleDateFormat.setLenient(false): strictly parses the date. If the date is unqualified, an exception will be thrown and will not be automatically calculated.

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of Java determines whether the date is legal. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!