Liberal date/time parsing in Joda-Time

会有一股神秘感。 提交于 2019-12-10 17:33:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!