I am having string like
"11-04-2015 22:01:13:053" or "32476347656435"
How can I check if string is Date?
Checking String if it is numeric using regex
String regex = "[0-9]+";
Other person are also correct
This is your answer
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class date {
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:ms");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isValidDate("20-01-2014"));
System.out.println(isValidDate("11-04-2015 22:01:33:023"));
System.out.println(isValidDate("32476347656435"));
}
}
It’s about time someone provides the modern answer. The SimpleDateFormat
class mentioned in a couple of the other answers is notoriously troublesome and fortunately now long outdated. Instead the modern solution uses java.time, the modern Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss:SSS");
String stringToTest = "11-04-2015 22:01:13:053";
try {
LocalDateTime dateTime = LocalDateTime.parse(stringToTest, formatter);
System.out.println("The string is a date and time: " + dateTime);
} catch (DateTimeParseException dtpe) {
System.out.println("The string is not a date and time: " + dtpe.getMessage());
}
Output from this snippet is:
The string is a date and time: 2015-04-11T22:01:13.053
Suppose that instead the string was defined as:
String stringToTest = "32476347656435";
Now the output is:
The string is not a date and time: Text '32476347656435' could not be parsed at index 2
Link: Oracle tutorial: Date Time explaining how to use java.time.
There are two possible solutions:
SimpleDateFormat
and try to convert the String
to Date
. If no ParseException
is thrown the format is correct.String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With