简体   繁体   English

如何使用String的split方法验证日期?

[英]How do I validate a date using split method of String?

How do I validate a date(i mean that the date should not be invalid) using split method of string class? 如何使用字符串类的split方法验证日期(我的意思是该日期不应无效)? Further details: Each month should have their respective days and February should have 29 days only when it is a leap year and date should not exceed the present date. 进一步的详细信息:每个月应有各自的日期,而2月仅在when年且日期不能超过当前日期时才应有29天。

I can recomment to use validate(String value) method from Apache Commons DateValidator : 我可以建议使用Apache Commons DateValidator中的 validate(String value)方法:

import org.apache.commons.validator.routines.DateValidator;
...

// Get the Date validator
DateValidator validator = DateValidator.getInstance();

// Validate/Convert the date
Date fooDate = validator.validate(fooString);
if (fooDate == null) {
    // error...not a valid date
    return;
}

validate() returns parsed Date if valid or null if invalid. validate()如果有效,则返回已解析的Date;如果无效,则返回null。

If you want only to get true/false, then there is another boolean method isValid() . 如果只想得到true / false,那么还有另一个布尔方法isValid() For example: 例如:

DateValidator validator = DateValidator.getInstance();
if (validator.isValid(date)) {
    System.out.println(date + " is valid");
} else {
    System.out.println(date + " is invalid");
}

In the JDK, you have SimpleDateFormat to handle this kind of stuff. 在JDK中,您具有SimpleDateFormat来处理这种事情。

For instance, to validate an hour: 例如,要验证一个小时:

final DateFormat fmt = new SimpleDateFormat("HH:mm");

Then you can try and parse: 然后,您可以尝试解析:

fmt.parse(input);

It will throw a ParseException if the date is invalid. 如果日期无效,它将抛出ParseException

Of course, many other formats can be done. 当然,可以使用许多其他格式。

As to external libraries, if you have to/want to use one, there is really only one to consider: Joda Time . 对于外部库,如果您必须/想要使用一个,那么实际上只需要考虑一个: Joda Time It is so good a library that Java 8's new date API is 90+% inspired by it. 它是如此出色,以至于Java 8的新日期API受到了90%以上的启发。

NOTE: JDK's as well as Joda Time's, parsers will derive missing components in a date from the current time; 注意:JDK和Joda Time的解析器将从当前时间的某个日期中导出缺少的组件; it means that if you try and parse a string containing Feb 29 in 2015, it will fail... But it will succeed in 2016 since it is a leap year! 这意味着,如果您尝试在2015年解析包含Feb 29日的字符串,它将失败。但是由于it年,它将在2016年成功!

convert string to date format, and this is easy for validating 

public class DateUtil {

    // List of all date formats that we want to parse.
    // Add your own format here.
//u can use anyone format
    private static List<SimpleDateFormat>; 
            dateFormats = new ArrayList<SimpleDateFormat>() {{
            add(new SimpleDateFormat("M/dd/yyyy"));
            add(new SimpleDateFormat("dd.M.yyyy"));
            add(new SimpleDateFormat("dd.M.yyyy hh:mm:ss a"));
            add(new SimpleDateFormat("dd.MMM.yyyy"));
            add(new SimpleDateFormat("dd-MMM-yyyy"));
        }
    };

    /**
     * Convert String with various formats into java.util.Date
     * 
     * @param input
     *            Date as a string
     * @return java.util.Date object if input string is parsed 
     *          successfully else returns null
     */
    public static Date convertToDate(String input) {
        Date date = null;
        if(null == input) {
            return null;
        }
        for (SimpleDateFormat format : dateFormats) {
            try {
                format.setLenient(false);
                date = format.parse(input);
            } catch (ParseException e) {
                //Shhh.. try other formats
            }
            if (date != null) {
                break;
            }
        }

        return date;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM