【发布时间】:2010-08-02 09:33:06
【问题描述】:
我想在 Java 中用这种格式解析字符串的最佳方法是什么 dd/MM/yyyy [到 dd/MM/yyyy]。带有 [] 的字符串是可选的,dd 代表日期的 2 位数表示,MM 表示月份的 2 位数表示,yyyy 表示年份的 4 位数表示。
更新
感谢大家的快速响应,但是我忘了告诉你 [] 是表示可选的,字符串中没有 [] 示例字符串可能是
- 22/01/2010
- 22/01/2010 至 23/01/2010
- 空
目前我是这样写代码的,可以工作但是很丑=(
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, the modern Java date and time API 的LocalDate和DateTimeFormatter。详情请见the answer by Basil Bourque。