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();
Here's a simple method:
For example, if you want the date format to be "03.11.2017"
You can try this to simple date format valdation
A combination of the regex and SimpleDateFormat is the right answer i believe. SimpleDateFormat does not catch exception if the individual components are invalid meaning, Format Defined: yyyy-mm-dd input: 201-0-12 No exception will be thrown.This case should have been handled. But with the regex as suggested by Sok Pomaranczowy and Baby will take care of this particular case.
Regex can be used for this with some detailed info for validation, for example this code can be used to validate any date in (DD/MM/yyyy) format with proper date and month value and year between (1950-2050)
Disclaimer
Parsing a string back to date/time value in an unknown format is inherently impossible (let's face it, what does
3/3/3
actually mean?!), all we can do is "best effort"Important
This solution doesn't throw an
Exception
, it returns aboolean
, this is by design. AnyException
s are used purely as a guard mechanism.2018
Since it's now 2018 and Java 8+ has the date/time API (and the rest have the ThreeTen backport). The solution remains basically the same, but becomes slightly more complicated, as we need to perform checks for:
This makes it look something like...
This makes the following...
output...
Original Answer
Simple try and parse the
String
to the requiredDate
using something likeSimpleDateFormat
You could then simply write a simple method that performed this action and returned
true
when everDate
was not null...As a suggestion...
Updated with running example
I'm not sure what you are doing, but, the following example...
Outputs (something like)...
Seems to work as expected for me - the method doesn't rely on (nor does it throw) the exception alone to perform it's operation