Package net.time4j

Class Duration.Formatter<U extends IsoUnit>

java.lang.Object
net.time4j.format.TimeSpanFormatter<U,​Duration<U>>
net.time4j.Duration.Formatter<U>
Type Parameters:
U - generic type of time units
Enclosing class:
Duration<U extends IsoUnit>

public static final class Duration.Formatter<U extends IsoUnit> extends TimeSpanFormatter<U,​Duration<U>>

Non-localized and user-defined format for durations based on a pattern containing some standard symbols and literals.

Note: For storing purposes users should normally use the canonical or ISO- or XML-representation of a duration, not this custom format. Otherwise, if users want a localized output then the class PrettyTime is usually the best choice. This class is mainly designed for handling non-standardized formats.

First example (parsing a Joda-Time-Period using a max width of 2):

  Duration.Formatter<IsoUnit> f = Duration.Formatter.ofJodaStyle();
  Duration<?> dur = f.parse("P-2Y-15DT-30H-5M");
  System.out.println(dur); // output: -P2Y15DT30H5M
 

Second example (printing a wall-time-like duration):

  Duration.Formatter<ClockUnit> f =
      Duration.Formatter.ofPattern(ClockUnit.class, "+hh:mm:ss");
  String s = f.print(Duration.ofClockUnits(27, 30, 5));
  System.out.println(s); // output: +27:30:05
 
Since:
1.2
See Also:
Duration.toString(), Duration.parsePeriod(String), ofPattern(Class, String)
  • Method Details

    • ofJodaStyle

      public static Duration.Formatter<IsoUnit> ofJodaStyle()

      Handles Joda-Time-style-patterns which in general follow XML-schema - with the exception of sign handling.

      The sign handling of Joda-Time allows and even enforces in contrast to XML-schema negative signs not before the P-symbol but for every single duration item repeatedly. Warning: Mixed signs are never supported by Time4J.

      Returns:
      new formatter instance for parsing Joda-Style period expressions
      Since:
      3.0
      See Also:
      ofPattern(Class, String)
    • ofPattern

      public static Duration.Formatter<IsoUnit> ofPattern(String pattern)

      Equivalent to ofPattern(IsoUnit.class, pattern).

      Parameters:
      pattern - format pattern
      Returns:
      new formatter instance
      Throws:
      IllegalArgumentException - in any case of pattern inconsistencies or failures
      Since:
      1.2
      See Also:
      ofPattern(Class, String)
    • ofPattern

      public static <U extends IsoUnit> Duration.Formatter<U> ofPattern(Class<U> type, String pattern)

      Constructs a new instance of duration formatter.

      Uses a pattern with symbols as followed:
       

      Legend
      SymbolDescription
      +sign of duration, printing + or -
      -sign of duration, printing only -
      ICalendarUnit.MILLENNIA
      CCalendarUnit.CENTURIES
      ECalendarUnit.DECADES
      YCalendarUnit.YEARS
      QCalendarUnit.QUARTERS
      MCalendarUnit.MONTHS
      WCalendarUnit.WEEKS
      DCalendarUnit.DAYS
      hClockUnit.HOURS
      mClockUnit.MINUTES
      sClockUnit.SECONDS
      ,decimal separator, comma is preferred
      .decimal separator, dot is preferred
      f ClockUnit.NANOS as fraction, (1-9) chars
      'apostroph, for escaping literal chars
      []optional section
      {}section with plural forms, since v2.0
      #placeholder for an optional digit, since v3.0
      |joins two parsing sections by or-logic, since v3.26/4.22

      All letters in range a-z and A-Z are always reserved chars and must be escaped by apostrophes for interpretation as literals. If such a letter is repeated then the count of symbols controls the minimum width for formatted output. Such a minimum width also reserves this area for parsing of any preceding item. If necessary a number (of units) will be padded from left with the zero digit. The unit symbol (with exception of "f") can be preceded by any count of char "#" (>= 0). The sum of min width and count of #-chars define the maximum width for formatted output and parsing.

      Optional sections

      Optional sections enclosed by square brackets let the parser be error-tolerant and continue with the next section in case of errors. Since v2.3: During printing, an optional section will only be printed if there is any non-zero part. When parsing an optional section will be skipped if the input to be parsed does not match the expected pattern. For example: An input missing the hour part can be handled when an optional section is applied on the hour part.

      Enhancement since version v2.0: plural forms

      Every expression inside curly brackets represents a combination of amount, separator and pluralized unit name and has following syntax:

      {[symbol]:[separator]:[locale]:[CATEGORY=LITERAL][:...]}

      The symbol is one of following chars: I, C, E, Y, Q, M, W, D, h, m, s, f (legend see table above)

      Afterwards the definition of separator chars follows. The empty separator (represented by zero space between colons) is permitted, too. The next section denotes the locale necessary for determination of suitable plural rules. The form [language]-[country]-[variant] can be used, for example "en-US" or "en_US". At least the language must be present. The underscore is an acceptable alternative for the minus-sign. Finally there must be a sequence of name-value-pairs in the form CATEGORY=LITERAL. Every category label must be the name of a plural category. The category OTHER must exist. Example:

        Duration.Formatter<CalendarUnit> formatter =
            Duration.Formatter.ofPattern(
                CalendarUnit.class,
                "{D: :en:ONE=day:OTHER=days}");
        String s = formatter.format(Duration.of(3, DAYS));
        System.out.println(s); // output: 3 days
       

      Enhancement since version v3.0: numerical placeholders

      Before version v3.0, the maximum numerical width was always 18. Now it is the sum of min width and the count of preceding #-chars. Example:

        Duration.Formatter<CalendarUnit> formatter1 =
            Duration.Formatter.ofPattern(CalendarUnit.class, "D");
        formatter1.format(Duration.of(123, DAYS)); throws IllegalArgumentException
      
        Duration.Formatter<CalendarUnit> formatter2 =
            Duration.Formatter.ofPattern(CalendarUnit.class, "##D");
        String s = formatter2.format(Duration.of(123, DAYS));
        System.out.println(s); // output: 123
       

      Enhancement since version v3.26/4.22: or-logic

      The character "|" starts a new section which will not be used for printing but parsing in case of preceding errors. For example, following pattern enables parsing a duration in days for two different languages:

        "{D: :en:ONE=day:OTHER=days}|{D: :de:ONE=Tag:OTHER=Tage}"
       
      Type Parameters:
      U - generic unit type
      Parameters:
      type - reified unit type
      pattern - format pattern
      Returns:
      new formatter instance
      Throws:
      IllegalArgumentException - in any case of pattern inconsistencies or failures
      Since:
      1.2
    • format

      public String format(TemporalAmount threeten)

      Creates a textual output of given temporal amount.

      Parameters:
      threeten - temporal amount
      Returns:
      textual representation of duration
      Throws:
      IllegalArgumentException - if some aspects of temporal amount prevents printing (for example mixed signs)
      Since:
      4.0
      See Also:
      Duration.from(TemporalAmount)
    • print

      public void print(TemporalAmount threeten, Appendable buffer) throws IOException

      Creates a textual output of given temporal amount and writes to the buffer.

      Parameters:
      threeten - temporal amount
      buffer - I/O-buffer where the result is written to
      Throws:
      IllegalArgumentException - if some aspects of temporal amount prevents printing (for example mixed signs)
      IOException - if writing into buffer fails
      Since:
      4.0
      See Also:
      Duration.from(TemporalAmount)