问题
Is it possible to create a single DateTimeParser
which would parse:
- dates with time given
- dates without time (assuming time to be start of day)
- times without dates (assuming date to be today)
or do I need to have three separate parsers, and try parsing strings with each one?
In other words, is it possible to define optional fields in a parser?
回答1:
org.joda.time.format.ISODateTimeFormat
has a static method dateOptionalTimeParser()
that uses the code below, based on the DateTimeFomatterBuilder
class, which has an appendOptional
method - you would probably be able to adapt the method to your requirement... Link: http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormatterBuilder.html
public static DateTimeFormatter dateOptionalTimeParser() {
if (dotp == null) {
DateTimeParser timeOrOffset = new DateTimeFormatterBuilder()
.appendLiteral('T')
.appendOptional(timeElementParser().getParser())
.appendOptional(offsetElement().getParser())
.toParser();
dotp = new DateTimeFormatterBuilder()
.append(dateElementParser())
.appendOptional(timeOrOffset)
.toFormatter();
}
return dotp;
}
来源:https://stackoverflow.com/questions/9308977/liberal-date-time-parsing-in-joda-time