我想使用 DateUtils.parseDate
解析具有不同潜在格式的日期。它似乎使用了第一个解析器,即使它应该检测到 23/10/2014
和 2014/10/23
之间的区别。
它实际上会解析日期,即使它是错误的,以至于我什至无法捕捉到异常。我能怎么做?这是一个错误吗? (commons-lang3-3.3.2)
这是一段代码
package snippet;
import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
public class TestDateFormat {
public static void main(String[] args) throws ParseException {
Date d = DateUtils.parseDate("23/10/2014T12:34:22",
new String[] {"yyyy/MM/dd'T'HH:mm:ss",
"dd/MM/yyyy'T'HH:mm:ss"});
System.out.println(d);
//returns Tue Apr 05 12:34:22 CET 29 which is wrong
}
}
最佳答案
你应该使用DateUtils.parseDateStrictly
:
Parses a string representing a date by trying a variety of different parsers.
The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.
The parser parses strictly - it does not allow for dates such as "February 942, 1996".
在内部,它所做的是将使用的 DateFormat
的 lenient
属性设置为 false
:DateFormat.html#setLenient
Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.
例子:
public static void main(String[] args) throws ParseException {
Date d = DateUtils.parseDateStrictly("23/10/2014T12:34:22",
new String[] {"yyyy/MM/dd'T'HH:mm:ss",
"dd/MM/yyyy'T'HH:mm:ss"});
System.out.println(d);
}
关于java - Apache DateUtils : parsing a date with multiple patterns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26712834/