Here’s the Java 8 solution (it can be made to work in Java 6 and 7 too when you use the ThreeTen Backport).
private static final DateTimeFormatter DATE_TIME_FORMAT
= DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss")
.withResolverStyle(ResolverStyle.STRICT);
public static boolean hasTypeDate(String stringFromTxt) {
try {
DATE_TIME_FORMAT.parse(stringFromTxt);
return true;
} catch (DateTimeParseException dtpe) {
return false;
}
}
Stay away from SimpleDateFormat
for new code. It has had its time, it’s been outdated for a while now.
If you intended the day of month first (if 02/01/2017
means January 2nd), you need the format pattern dd/MM/uuuu HH:mm:ss
instead.
If you need to know which date and time was in the .txt
, use:
LocalDateTime dateTime = LocalDateTime.parse(stringFromTxt, DATE_TIME_FORMAT);
Link: ThreeTen Backport: java.time
classes for Java 6 and 7.