Java: Check the date format of current string is according to required format or not [duplicate]
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();
Solution 1:
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 a boolean
, this is by design. Any Exception
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:
- date and time
- date only
- time only
This makes it look something like...
public static boolean isValidFormat(String format, String value, Locale locale) {
LocalDateTime ldt = null;
DateTimeFormatter fomatter = DateTimeFormatter.ofPattern(format, locale);
try {
ldt = LocalDateTime.parse(value, fomatter);
String result = ldt.format(fomatter);
return result.equals(value);
} catch (DateTimeParseException e) {
try {
LocalDate ld = LocalDate.parse(value, fomatter);
String result = ld.format(fomatter);
return result.equals(value);
} catch (DateTimeParseException exp) {
try {
LocalTime lt = LocalTime.parse(value, fomatter);
String result = lt.format(fomatter);
return result.equals(value);
} catch (DateTimeParseException e2) {
// Debugging purposes
//e2.printStackTrace();
}
}
}
return false;
}
This makes the following...
System.out.println("isValid - dd/MM/yyyy with 20130925 = " + isValidFormat("dd/MM/yyyy", "20130925", Locale.ENGLISH));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 = " + isValidFormat("dd/MM/yyyy", "25/09/2013", Locale.ENGLISH));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = " + isValidFormat("dd/MM/yyyy", "25/09/2013 12:13:50", Locale.ENGLISH));
System.out.println("isValid - yyyy-MM-dd with 2017-18--15 = " + isValidFormat("yyyy-MM-dd", "2017-18--15", Locale.ENGLISH));
output...
isValid - dd/MM/yyyy with 20130925 = false
isValid - dd/MM/yyyy with 25/09/2013 = true
isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = false
isValid - yyyy-MM-dd with 2017-18--15 = false
Original Answer
Simple try and parse the String
to the required Date
using something like SimpleDateFormat
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
} catch (ParseException ex) {
ex.printStackTrace();
}
if (date == null) {
// Invalid date format
} else {
// Valid date format
}
You could then simply write a simple method that performed this action and returned true
when ever Date
was not null...
As a suggestion...
Updated with running example
I'm not sure what you are doing, but, the following example...
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateParser {
public static void main(String[] args) {
System.out.println("isValid - dd/MM/yyyy with 20130925 = " + isValidFormat("dd/MM/yyyy", "20130925"));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 = " + isValidFormat("dd/MM/yyyy", "25/09/2013"));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = " + isValidFormat("dd/MM/yyyy", "25/09/2013 12:13:50"));
}
public static boolean isValidFormat(String format, String value) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
} catch (ParseException ex) {
ex.printStackTrace();
}
return date != null;
}
}
Outputs (something like)...
java.text.ParseException: Unparseable date: "20130925"
isValid - dd/MM/yyyy with 20130925 = false
isValid - dd/MM/yyyy with 25/09/2013 = true
isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = false
at java.text.DateFormat.parse(DateFormat.java:366)
at javaapplication373.JavaApplication373.isValidFormat(JavaApplication373.java:28)
at javaapplication373.JavaApplication373.main(JavaApplication373.java:19)
Not correct. For isValidFormat("yyyy-MM-dd", "2017-18--15"); not throw any Exception.
isValid - yyyy-MM-dd", "2017-18--15 = false
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
Solution 2:
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
Solution 3:
You can try this to simple date format valdation
public Date validateDateFormat(String dateToValdate) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HHmmss");
//To make strict date format validation
formatter.setLenient(false);
Date parsedDate = null;
try {
parsedDate = formatter.parse(dateToValdate);
System.out.println("++validated DATE TIME ++"+formatter.format(parsedDate));
} catch (ParseException e) {
//Handle exception
}
return parsedDate;
}
Solution 4:
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;
}
Solution 5:
Here's a simple method:
public static boolean checkDatePattern(String padrao, String data) {
try {
SimpleDateFormat format = new SimpleDateFormat(padrao, LocaleUtils.DEFAULT_LOCALE);
format.parse(data);
return true;
} catch (ParseException e) {
return false;
}
}