The solution with RegEx is good, but you can also do in this way:
The first parameter is your string representation of the date. The next parameter is var arg. So you can pass as many date formats as you wish. It will try to parse and if success then returns proper format.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
Optional<String> format = test("07-01-2017", "dd/mm/yyyy", "dd-mm-yyyy");
if (format.isPresent())
System.out.println(format.get());
}
public static Optional<String> test(String date, String... formats) {
return Stream.of(formats)
.map(format -> new Pair<>(new SimpleDateFormat(format), format))
.map(p -> {
try {
p._1.parse(date);
return p._2;
} catch (ParseException e) {
return null;
}
})
.filter(Objects::nonNull)
.findFirst();
}
public static class Pair<F, S> {
public final F _1;
public final S _2;
public Pair(F _1, S _2) {
this._1 = _1;
this._2 = _2;
}
}
}