更新
谢谢大家的快速回复,但我忘了告诉你们[]是表示可选的符号,在字符串中没有[],样例字符串可能如下:
- 22/01/2010
- 22/01/2010 to 23/01/2010
- null
目前我写的代码是这样的,虽然能用但很丑 =(
String _daterange = (String) request.getParameter("daterange");
Date startDate = null, endDate = null;
// Format of incoming dateRange is
if (InputValidator.requiredValidator(_daterange)) {
String[] _dateRanges = _daterange.toUpperCase().split("TO");
try {
startDate = (_dateRanges.length > 0) ? sdf.parse(_dateRanges[0]) : null;
try{
endDate = (_dateRanges.length > 1) ? sdf.parse(_dateRanges[1]) : null;
}catch(Exception e){
endDate = null;
}
} catch (Exception e) {
startDate = null;
}
}
Date
和SimpleDateFormat
。这些类设计得很差,而且早已过时,后者尤其麻烦。相反,应该使用来自java.time,现代Java日期和时间API的LocalDate
和DateTimeFormatter
。有关详细信息,请参见Basil Bourque的答案。 - Ole V.V.