A generic Date utility that accepts date in ymd or dmy format.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateUtils {
private static final Pattern ymd = Pattern
.compile("^(\\d{4})-([1-9]|[0][1-9]|1[0-2])
-([1-9]|0[1-9]|[12][0-9]|[3][01])$");
private static final Pattern dmy = Pattern
.compile("^([1-9]|[0][1-9]|1[0-2])
-([1-9]|0[1-9]|[12][0-9]|[3][01])-(\\d{4})$");
private static final DateFormat df = new SimpleDateFormat(
"yyyy-MM-dd");
static {
//prevents using "2001-02-29" for March 1st
df.setLenient(false);
}
private static Date parse(String value) {
if (value == null) {
return null;
}
String input = value.trim().replaceAll("[\\./ ]", "-");
if (input.length() < 8) {
return null;
}
String ds = null;
Matcher matcher = ymd.matcher(input);
if (matcher.find()) {
ds = matcher.group(1) + "-" + matcher.group(2) + "-"
+ matcher.group(3);
} else {
matcher = dmy.matcher(input);
if (matcher.find()) {
ds = matcher.group(3) + "-" + matcher.group(1) + "-"
+ matcher.group(2);
}
}
Date result = null;
if (ds == null) {
// user's inputer does not match an expected format
} else {
try {
result = df.parse(ds);
} catch (ParseException e1) {
// should not happen, but treat it the same as invalid input
// there is no need to log
}
}
return result;
}
public static void main(String[] args) {
String[] inputs = { "2016-9-8", "2016-09-8", "2016-09-08", "2016-9-08",
"9-8-2016", "09-8-2016", "09-08-2016", "9-08-2016", "9/8/2016",
" 9-8-2016", " 2016-9-8", "9-8-2016 ", "2016-9-8 ",
"2016 9 8 ",
null, "13-1-9999", "1-33-9999", "9999-13-1", "9999-1-33" };
for (String input : inputs) {
System.err.println(input + "\t" + parse(input));
}
}
}
No comments:
Post a Comment