Home > Java > JavaBase > body text

Java determines whether a string is a legal date

Release: 2019-12-02 11:27:59
Original
3720 people have browsed it

Java determines whether a string is a legal date

Determine whether a string like "2018-02-30" is a correct and reasonable date: (Recommended: java video tutorial)

 //假设传入的日期格式是yyyy-MM-dd HH:mm:ss, 也可以传入yyyy-MM-dd,如2018-1-1或者2018-01-01格式
 
    public static boolean isValidDate(String strDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2018-02-29会被接受,并转换成2018-03-01 
            
            format.setLenient(false);
            Date date = format.parse(strDate);
            
            //判断传入的yyyy年-MM月-dd日 字符串是否为数字
            String[] sArray = strDate.split("-");
            for (String s : sArray) {
                boolean isNum = s.matches("[0-9]+");
                //+表示1个或多个(如"3"或"225"),*表示0个或多个([0-9]*)(如""或"1"或"22"),?表示0个或1个([0-9]?)(如""或"7")
                if (!isNum) {
                    return false;
                }
            }
        } catch (Exception e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            return false;
        }
 
        return true;
    }
Copy after login

SimpleDateFormat class

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-dependent manner, which allows formatting (date → text), parsing ( text → date) and normalization. SimpleDateFormat enables the selection of any user-defined date/time format pattern.

The SimpleDateFormat class mainly has the following three construction methods.

SimpleDateFormat(): Constructs SimpleDateFormat with the default format and default locale.

SimpleDateFormat(String pattern): Constructs SimpleDateF ormat with the specified format and default locale.

SimpleDateFormat(String pattern,Locale locale): Constructs SimpleDateF ormat with the specified format and the specified locale.

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

The above is the detailed content of Java determines whether a string is a legal date. 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