Liberal parsing of date and time in Joda-Time

Is it possible to create one DateTimeParser that will parse:

  • dates with time
  • dates without time (assuming time will be the beginning of the day)
  • times without dates (expected date should be today)

or do I need to have three separate parsers and try parsing strings with each of them?

In other words, is it possible to define optional fields in the parser?

+4
source share
1 answer

org.joda.time.format.ISODateTimeFormat has a static dateOptionalTimeParser() method that uses the following code based on the DateTimeFomatterBuilder class which has an appendOptional method - you can probably 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; } 
+3
source

Source: https://habr.com/ru/post/1396799/


All Articles