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; } }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software