Java: Check the date format of current string is a

2020-01-23 04:07发布

I wanted to know that is there any method available in Java that can do this.Otherwise I may go for Regex solution.

I have input string from user that can be any characters. And I want to check that the input string is according to my required date format or not.

As I have input 20130925 and my required format is dd/MM/yyyy so, for this case I should get false.

I don't want to convert this date I just want to check whether input string is according to required date format or not.



I have tried following

Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yyyy").parse("20130925");
} catch (Exception ex) {
// do something for invalid dateformat
}

but my catch (Exception ex) block is unable to catch any exceptions generated by SimpleDateFormat.Parse();

标签: java date
8条回答
唯我独甜
2楼-- · 2020-01-23 04:36

For your case, you may use regex:

boolean checkFormat;

if (input.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
    checkFormat=true;
else
   checkFormat=false;

For a larger scope or if you want a flexible solution, refer to MadProgrammer's answer.

Edit

Almost 5 years after posting this answer, I realize that this is a stupid way to validate a date format. But i'll just leave this here to tell people that using regex to validate a date is unacceptable

查看更多
不美不萌又怎样
3楼-- · 2020-01-23 04:38
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
formatter.setLenient(false);
try {
    Date date= formatter.parse("02/03/2010");
} catch (ParseException e) {
    //If input date is in different format or invalid.
}

formatter.setLenient(false) will enforce strict matching.

If you are using Joda-Time -

private boolean isValidDate(String dateOfBirth) {
        boolean valid = true;
        try {
            DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
            DateTime dob = formatter.parseDateTime(dateOfBirth);
        } catch (Exception e) {
            valid = false;
        }
        return valid;
    }
查看更多
登录 后发表回答