DurationFormatUtils.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.lang3.time;

  18. import java.text.SimpleDateFormat;
  19. import java.util.ArrayList;
  20. import java.util.Calendar;
  21. import java.util.Date;
  22. import java.util.GregorianCalendar;
  23. import java.util.Objects;
  24. import java.util.TimeZone;
  25. import java.util.stream.Stream;

  26. import org.apache.commons.lang3.StringUtils;
  27. import org.apache.commons.lang3.Validate;

  28. /**
  29.  * Duration formatting utilities and constants. The following table describes the tokens
  30.  * used in the pattern language for formatting.
  31.  * <table border="1">
  32.  *  <caption>Pattern Tokens</caption>
  33.  *  <tr><th>character</th><th>duration element</th></tr>
  34.  *  <tr><td>y</td><td>years</td></tr>
  35.  *  <tr><td>M</td><td>months</td></tr>
  36.  *  <tr><td>d</td><td>days</td></tr>
  37.  *  <tr><td>H</td><td>hours</td></tr>
  38.  *  <tr><td>m</td><td>minutes</td></tr>
  39.  *  <tr><td>s</td><td>seconds</td></tr>
  40.  *  <tr><td>S</td><td>milliseconds</td></tr>
  41.  *  <tr><td>'text'</td><td>arbitrary text content</td></tr>
  42.  * </table>
  43.  *
  44.  * <b>Note: It's not currently possible to include a single-quote in a format.</b>
  45.  * <br>
  46.  * Token values are printed using decimal digits.
  47.  * A token character can be repeated to ensure that the field occupies a certain minimum
  48.  * size. Values will be left-padded with 0 unless padding is disabled in the method invocation.
  49.  * <br>
  50.  * Tokens can be marked as optional by surrounding them with brackets [ ]. These tokens will
  51.  * only be printed if the token value is non-zero. Literals within optional blocks will only be
  52.  * printed if the preceding non-literal token is non-zero. Leading optional literals will only
  53.  * be printed if the following non-literal is non-zero.
  54.  * Multiple optional blocks can be used to group literals with the desired token.
  55.  * <p>
  56.  * Notes on Optional Tokens:<br>
  57.  * <b>Multiple optional tokens without literals can result in impossible to understand output.</b><br>
  58.  * <b>Patterns where all tokens are optional can produce empty strings.</b><br>
  59.  * (See examples below)
  60.  * </p>
  61.  * <br>
  62.  * <table border="1">
  63.  * <caption>Example Output</caption>
  64.  * <tr><th>pattern</th><th>Duration.ofDays(1)</th><th>Duration.ofHours(1)</th><th>Duration.ofMinutes(1)</th><th>Duration.ZERO</th></tr>
  65.  * <tr><td>d'd'H'h'm'm's's'</td><td>1d0h0m0s</td><td>0d1h0m0s</td><td>0d0h1m0s</td><td>0d0h0m0s</td></tr>
  66.  * <tr><td>d'd'[H'h'm'm']s's'</td><td>1d0s</td><td>0d1h0s</td><td>0d1m0s</td><td>0d0s</td></tr>
  67.  * <tr><td>[d'd'H'h'm'm']s's'</td><td>1d0s</td><td>1h0s</td><td>1m0s</td><td>0s</td></tr>
  68.  * <tr><td>[d'd'H'h'm'm's's']</td><td>1d</td><td>1h</td><td>1m</td><td></td></tr>
  69.  * <tr><td>['{'d'}']HH':'mm</td><td>{1}00:00</td><td>01:00</td><td>00:01</td><td>00:00</td></tr>
  70.  * <tr><td>['{'dd'}']['&lt;'HH'&gt;']['('mm')']</td><td>{01}</td><td>&lt;01&gt;</td><td>(00)</td><td></td></tr>
  71.  * <tr><td>[dHms]</td><td>1</td><td>1</td><td>1</td><td></td></tr>
  72.  * </table>
  73.  * <b>Note: Optional blocks cannot be nested.</b>
  74.  *
  75.  * @since 2.1
  76.  */
  77. public class DurationFormatUtils {

  78.     /**
  79.      * Element that is parsed from the format pattern.
  80.      */
  81.     static class Token {

  82.         /** Empty array. */
  83.         private static final Token[] EMPTY_ARRAY = {};

  84.         /**
  85.          * Helper method to determine if a set of tokens contain a value
  86.          *
  87.          * @param tokens set to look in
  88.          * @param value to look for
  89.          * @return boolean {@code true} if contained
  90.          */
  91.         static boolean containsTokenWithValue(final Token[] tokens, final Object value) {
  92.             return Stream.of(tokens).anyMatch(token -> token.getValue() == value);
  93.         }

  94.         private final CharSequence value;
  95.         private int count;
  96.         private int optionalIndex = -1;

  97.         /**
  98.          * Wraps a token around a value. A value would be something like a 'Y'.
  99.          *
  100.          * @param value value to wrap, non-null.
  101.          * @param optional whether the token is optional
  102.          * @param optionalIndex the index of the optional token within the pattern
  103.          */
  104.         Token(final CharSequence value, final boolean optional, final int optionalIndex) {
  105.             this.value = Objects.requireNonNull(value, "value");
  106.             this.count = 1;
  107.             if (optional) {
  108.                 this.optionalIndex = optionalIndex;
  109.             }
  110.         }

  111.         /**
  112.          * Supports equality of this Token to another Token.
  113.          *
  114.          * @param obj2 Object to consider equality of
  115.          * @return boolean {@code true} if equal
  116.          */
  117.         @Override
  118.         public boolean equals(final Object obj2) {
  119.             if (obj2 instanceof Token) {
  120.                 final Token tok2 = (Token) obj2;
  121.                 if (this.value.getClass() != tok2.value.getClass()) {
  122.                     return false;
  123.                 }
  124.                 if (this.count != tok2.count) {
  125.                     return false;
  126.                 }
  127.                 if (this.value instanceof StringBuilder) {
  128.                     return this.value.toString().equals(tok2.value.toString());
  129.                 }
  130.                 if (this.value instanceof Number) {
  131.                     return this.value.equals(tok2.value);
  132.                 }
  133.                 return this.value == tok2.value;
  134.             }
  135.             return false;
  136.         }

  137.         /**
  138.          * Gets the current number of values represented
  139.          *
  140.          * @return int number of values represented
  141.          */
  142.         int getCount() {
  143.             return count;
  144.         }

  145.         /**
  146.          * Gets the particular value this token represents.
  147.          *
  148.          * @return Object value, non-null.
  149.          */
  150.         Object getValue() {
  151.             return value;
  152.         }

  153.         /**
  154.          * Returns a hash code for the token equal to the
  155.          * hash code for the token's value. Thus 'TT' and 'TTTT'
  156.          * will have the same hash code.
  157.          *
  158.          * @return The hash code for the token
  159.          */
  160.         @Override
  161.         public int hashCode() {
  162.             return this.value.hashCode();
  163.         }

  164.         /**
  165.          * Adds another one of the value
  166.          */
  167.         void increment() {
  168.             count++;
  169.         }

  170.         /**
  171.          * Represents this token as a String.
  172.          *
  173.          * @return String representation of the token
  174.          */
  175.         @Override
  176.         public String toString() {
  177.             return StringUtils.repeat(this.value.toString(), this.count);
  178.         }
  179.     }

  180.     private static final int MINUTES_PER_HOUR = 60;

  181.     private static final int SECONDS_PER_MINUTES = 60;

  182.     private static final int HOURS_PER_DAY = 24;

  183.     /**
  184.      * Pattern used with {@link FastDateFormat} and {@link SimpleDateFormat}
  185.      * for the ISO 8601 period format used in durations.
  186.      *
  187.      * @see org.apache.commons.lang3.time.FastDateFormat
  188.      * @see java.text.SimpleDateFormat
  189.      */
  190.     public static final String ISO_EXTENDED_FORMAT_PATTERN = "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.SSS'S'";

  191.     static final String y = "y";

  192.     static final String M = "M";

  193.     static final String d = "d";

  194.     static final String H = "H";

  195.     static final String m = "m";

  196.     static final String s = "s";

  197.     static final String S = "S";

  198.     /**
  199.      * The internal method to do the formatting.
  200.      *
  201.      * @param tokens  the tokens
  202.      * @param years  the number of years
  203.      * @param months  the number of months
  204.      * @param days  the number of days
  205.      * @param hours  the number of hours
  206.      * @param minutes  the number of minutes
  207.      * @param seconds  the number of seconds
  208.      * @param milliseconds  the number of millis
  209.      * @param padWithZeros  whether to pad
  210.      * @return the formatted string
  211.      */
  212.     static String format(final Token[] tokens, final long years, final long months, final long days, final long hours, final long minutes,
  213.             final long seconds,
  214.             final long milliseconds, final boolean padWithZeros) {
  215.         final StringBuilder buffer = new StringBuilder();
  216.         boolean lastOutputSeconds = false;
  217.         boolean lastOutputZero = false;
  218.         int optionalStart = -1;
  219.         boolean firstOptionalNonLiteral = false;
  220.         int optionalIndex = -1;
  221.         boolean inOptional = false;
  222.         for (final Token token : tokens) {
  223.             final Object value = token.getValue();
  224.             final boolean isLiteral = value instanceof StringBuilder;
  225.             final int count = token.getCount();
  226.             if (optionalIndex != token.optionalIndex) {
  227.               optionalIndex = token.optionalIndex;
  228.               if (optionalIndex > -1) {
  229.                 //entering new optional block
  230.                 optionalStart = buffer.length();
  231.                 lastOutputZero = false;
  232.                 inOptional = true;
  233.                 firstOptionalNonLiteral = false;
  234.               } else {
  235.                 //leaving optional block
  236.                 inOptional = false;
  237.               }
  238.             }
  239.             if (isLiteral) {
  240.                 if (!inOptional || !lastOutputZero) {
  241.                     buffer.append(value.toString());
  242.                 }
  243.             } else if (value.equals(y)) {
  244.                 lastOutputSeconds = false;
  245.                 lastOutputZero = years == 0;
  246.                 if (!inOptional || !lastOutputZero) {
  247.                     buffer.append(paddedValue(years, padWithZeros, count));
  248.                 }
  249.             } else if (value.equals(M)) {
  250.                 lastOutputSeconds = false;
  251.                 lastOutputZero = months == 0;
  252.                 if (!inOptional || !lastOutputZero) {
  253.                     buffer.append(paddedValue(months, padWithZeros, count));
  254.                 }
  255.             } else if (value.equals(d)) {
  256.                 lastOutputSeconds = false;
  257.                 lastOutputZero = days == 0;
  258.                 if (!inOptional || !lastOutputZero) {
  259.                     buffer.append(paddedValue(days, padWithZeros, count));
  260.                 }
  261.             } else if (value.equals(H)) {
  262.                 lastOutputSeconds = false;
  263.                 lastOutputZero = hours == 0;
  264.                 if (!inOptional || !lastOutputZero) {
  265.                     buffer.append(paddedValue(hours, padWithZeros, count));
  266.                 }
  267.             } else if (value.equals(m)) {
  268.                 lastOutputSeconds = false;
  269.                 lastOutputZero = minutes == 0;
  270.                 if (!inOptional || !lastOutputZero) {
  271.                     buffer.append(paddedValue(minutes, padWithZeros, count));
  272.                 }
  273.             } else if (value.equals(s)) {
  274.                 lastOutputSeconds = true;
  275.                 lastOutputZero = seconds == 0;
  276.                 if (!inOptional || !lastOutputZero) {
  277.                     buffer.append(paddedValue(seconds, padWithZeros, count));
  278.                 }
  279.             } else if (value.equals(S)) {
  280.                 lastOutputZero = milliseconds == 0;
  281.                 if (!inOptional || !lastOutputZero) {
  282.                     if (lastOutputSeconds) {
  283.                         // ensure at least 3 digits are displayed even if padding is not selected
  284.                         final int width = padWithZeros ? Math.max(3, count) : 3;
  285.                         buffer.append(paddedValue(milliseconds, true, width));
  286.                     } else {
  287.                         buffer.append(paddedValue(milliseconds, padWithZeros, count));
  288.                     }
  289.                 }
  290.                 lastOutputSeconds = false;
  291.             }
  292.             //as soon as we hit first nonliteral in optional, check for literal prefix
  293.             if (inOptional && !isLiteral && !firstOptionalNonLiteral) {
  294.                 firstOptionalNonLiteral = true;
  295.                 if (lastOutputZero) {
  296.                     buffer.delete(optionalStart, buffer.length());
  297.                 }
  298.             }
  299.         }
  300.         return buffer.toString();
  301.     }

  302.     /**
  303.      * Formats the time gap as a string, using the specified format, and padding with zeros.
  304.      *
  305.      * <p>This method formats durations using the days and lower fields of the
  306.      * format pattern. Months and larger are not used.</p>
  307.      *
  308.      * @param durationMillis  the duration to format
  309.      * @param format  the way in which to format the duration, not null
  310.      * @return the formatted duration, not null
  311.      * @throws IllegalArgumentException if durationMillis is negative
  312.      */
  313.     public static String formatDuration(final long durationMillis, final String format) {
  314.         return formatDuration(durationMillis, format, true);
  315.     }

  316.     /**
  317.      * Formats the time gap as a string, using the specified format.
  318.      * Padding the left-hand side side of numbers with zeroes is optional.
  319.      *
  320.      * <p>This method formats durations using the days and lower fields of the
  321.      * format pattern. Months and larger are not used.</p>
  322.      *
  323.      * @param durationMillis  the duration to format
  324.      * @param format  the way in which to format the duration, not null
  325.      * @param padWithZeros  whether to pad the left-hand side side of numbers with 0's
  326.      * @return the formatted duration, not null
  327.      * @throws IllegalArgumentException if durationMillis is negative
  328.      */
  329.     public static String formatDuration(final long durationMillis, final String format, final boolean padWithZeros) {
  330.         Validate.inclusiveBetween(0, Long.MAX_VALUE, durationMillis, "durationMillis must not be negative");

  331.         final Token[] tokens = lexx(format);

  332.         long days = 0;
  333.         long hours = 0;
  334.         long minutes = 0;
  335.         long seconds = 0;
  336.         long milliseconds = durationMillis;

  337.         if (Token.containsTokenWithValue(tokens, d)) {
  338.             days = milliseconds / DateUtils.MILLIS_PER_DAY;
  339.             milliseconds -= days * DateUtils.MILLIS_PER_DAY;
  340.         }
  341.         if (Token.containsTokenWithValue(tokens, H)) {
  342.             hours = milliseconds / DateUtils.MILLIS_PER_HOUR;
  343.             milliseconds -= hours * DateUtils.MILLIS_PER_HOUR;
  344.         }
  345.         if (Token.containsTokenWithValue(tokens, m)) {
  346.             minutes = milliseconds / DateUtils.MILLIS_PER_MINUTE;
  347.             milliseconds -= minutes * DateUtils.MILLIS_PER_MINUTE;
  348.         }
  349.         if (Token.containsTokenWithValue(tokens, s)) {
  350.             seconds = milliseconds / DateUtils.MILLIS_PER_SECOND;
  351.             milliseconds -= seconds * DateUtils.MILLIS_PER_SECOND;
  352.         }

  353.         return format(tokens, 0, 0, days, hours, minutes, seconds, milliseconds, padWithZeros);
  354.     }

  355.     /**
  356.      * Formats the time gap as a string.
  357.      *
  358.      * <p>The format used is ISO 8601-like: {@code HH:mm:ss.SSS}.</p>
  359.      *
  360.      * @param durationMillis  the duration to format
  361.      * @return the formatted duration, not null
  362.      * @throws IllegalArgumentException if durationMillis is negative
  363.      */
  364.     public static String formatDurationHMS(final long durationMillis) {
  365.         return formatDuration(durationMillis, "HH:mm:ss.SSS");
  366.     }

  367.     /**
  368.      * Formats the time gap as a string.
  369.      *
  370.      * <p>The format used is the ISO 8601 period format.</p>
  371.      *
  372.      * <p>This method formats durations using the days and lower fields of the
  373.      * ISO format pattern, such as P7D6TH5M4.321S.</p>
  374.      *
  375.      * @param durationMillis  the duration to format
  376.      * @return the formatted duration, not null
  377.      * @throws IllegalArgumentException if durationMillis is negative
  378.      */
  379.     public static String formatDurationISO(final long durationMillis) {
  380.         return formatDuration(durationMillis, ISO_EXTENDED_FORMAT_PATTERN, false);
  381.     }

  382.     /**
  383.      * Formats an elapsed time into a pluralization correct string.
  384.      *
  385.      * <p>This method formats durations using the days and lower fields of the
  386.      * format pattern. Months and larger are not used.</p>
  387.      *
  388.      * @param durationMillis  the elapsed time to report in milliseconds
  389.      * @param suppressLeadingZeroElements  suppresses leading 0 elements
  390.      * @param suppressTrailingZeroElements  suppresses trailing 0 elements
  391.      * @return the formatted text in days/hours/minutes/seconds, not null
  392.      * @throws IllegalArgumentException if durationMillis is negative
  393.      */
  394.     public static String formatDurationWords(
  395.         final long durationMillis,
  396.         final boolean suppressLeadingZeroElements,
  397.         final boolean suppressTrailingZeroElements) {

  398.         // This method is generally replaceable by the format method, but
  399.         // there are a series of tweaks and special cases that require
  400.         // trickery to replicate.
  401.         String duration = formatDuration(durationMillis, "d' days 'H' hours 'm' minutes 's' seconds'");
  402.         if (suppressLeadingZeroElements) {
  403.             // this is a temporary marker on the front. Like ^ in regexp.
  404.             duration = " " + duration;
  405.             String tmp = StringUtils.replaceOnce(duration, " 0 days", StringUtils.EMPTY);
  406.             if (tmp.length() != duration.length()) {
  407.                 duration = tmp;
  408.                 tmp = StringUtils.replaceOnce(duration, " 0 hours", StringUtils.EMPTY);
  409.                 if (tmp.length() != duration.length()) {
  410.                     duration = tmp;
  411.                     tmp = StringUtils.replaceOnce(duration, " 0 minutes", StringUtils.EMPTY);
  412.                     duration = tmp;
  413.                 }
  414.             }
  415.             if (!duration.isEmpty()) {
  416.                 // strip the space off again
  417.                 duration = duration.substring(1);
  418.             }
  419.         }
  420.         if (suppressTrailingZeroElements) {
  421.             String tmp = StringUtils.replaceOnce(duration, " 0 seconds", StringUtils.EMPTY);
  422.             if (tmp.length() != duration.length()) {
  423.                 duration = tmp;
  424.                 tmp = StringUtils.replaceOnce(duration, " 0 minutes", StringUtils.EMPTY);
  425.                 if (tmp.length() != duration.length()) {
  426.                     duration = tmp;
  427.                     tmp = StringUtils.replaceOnce(duration, " 0 hours", StringUtils.EMPTY);
  428.                     if (tmp.length() != duration.length()) {
  429.                         duration = StringUtils.replaceOnce(tmp, " 0 days", StringUtils.EMPTY);
  430.                     }
  431.                 }
  432.             }
  433.         }
  434.         // handle plurals
  435.         duration = " " + duration;
  436.         duration = StringUtils.replaceOnce(duration, " 1 seconds", " 1 second");
  437.         duration = StringUtils.replaceOnce(duration, " 1 minutes", " 1 minute");
  438.         duration = StringUtils.replaceOnce(duration, " 1 hours", " 1 hour");
  439.         duration = StringUtils.replaceOnce(duration, " 1 days", " 1 day");
  440.         return duration.trim();
  441.     }

  442.     /**
  443.      * Formats the time gap as a string, using the specified format.
  444.      * Padding the left-hand side side of numbers with zeroes is optional.
  445.      *
  446.      * @param startMillis  the start of the duration
  447.      * @param endMillis  the end of the duration
  448.      * @param format  the way in which to format the duration, not null
  449.      * @return the formatted duration, not null
  450.      * @throws IllegalArgumentException if startMillis is greater than endMillis
  451.      */
  452.     public static String formatPeriod(final long startMillis, final long endMillis, final String format) {
  453.         return formatPeriod(startMillis, endMillis, format, true, TimeZone.getDefault());
  454.     }

  455.     /**
  456.      * <p>Formats the time gap as a string, using the specified format.
  457.      * Padding the left-hand side side of numbers with zeroes is optional and
  458.      * the time zone may be specified.
  459.      *
  460.      * <p>When calculating the difference between months/days, it chooses to
  461.      * calculate months first. So when working out the number of months and
  462.      * days between January 15th and March 10th, it choose 1 month and
  463.      * 23 days gained by choosing January-&gt;February = 1 month and then
  464.      * calculating days forwards, and not the 1 month and 26 days gained by
  465.      * choosing March -&gt; February = 1 month and then calculating days
  466.      * backwards.</p>
  467.      *
  468.      * <p>For more control, the <a href="https://www.joda.org/joda-time/">Joda-Time</a>
  469.      * library is recommended.</p>
  470.      *
  471.      * @param startMillis  the start of the duration
  472.      * @param endMillis  the end of the duration
  473.      * @param format  the way in which to format the duration, not null
  474.      * @param padWithZeros  whether to pad the left-hand side side of numbers with 0's
  475.      * @param timezone  the millis are defined in
  476.      * @return the formatted duration, not null
  477.      * @throws IllegalArgumentException if startMillis is greater than endMillis
  478.      */
  479.     public static String formatPeriod(final long startMillis, final long endMillis, final String format, final boolean padWithZeros,
  480.             final TimeZone timezone) {
  481.         Validate.isTrue(startMillis <= endMillis, "startMillis must not be greater than endMillis");

  482.         // Used to optimize for differences under 28 days and
  483.         // called formatDuration(millis, format); however this did not work
  484.         // over leap years.
  485.         // TODO: Compare performance to see if anything was lost by
  486.         // losing this optimization.

  487.         final Token[] tokens = lexx(format);

  488.         // time zones get funky around 0, so normalizing everything to GMT
  489.         // stops the hours being off
  490.         final Calendar start = Calendar.getInstance(timezone);
  491.         start.setTime(new Date(startMillis));
  492.         final Calendar end = Calendar.getInstance(timezone);
  493.         end.setTime(new Date(endMillis));

  494.         // initial estimates
  495.         long milliseconds = end.get(Calendar.MILLISECOND) - start.get(Calendar.MILLISECOND);
  496.         int seconds = end.get(Calendar.SECOND) - start.get(Calendar.SECOND);
  497.         int minutes = end.get(Calendar.MINUTE) - start.get(Calendar.MINUTE);
  498.         int hours = end.get(Calendar.HOUR_OF_DAY) - start.get(Calendar.HOUR_OF_DAY);
  499.         int days = end.get(Calendar.DAY_OF_MONTH) - start.get(Calendar.DAY_OF_MONTH);
  500.         int months = end.get(Calendar.MONTH) - start.get(Calendar.MONTH);
  501.         int years = end.get(Calendar.YEAR) - start.get(Calendar.YEAR);

  502.         // each initial estimate is adjusted in case it is under 0
  503.         while (milliseconds < 0) {
  504.             milliseconds += DateUtils.MILLIS_PER_SECOND;
  505.             seconds -= 1;
  506.         }
  507.         while (seconds < 0) {
  508.             seconds += SECONDS_PER_MINUTES;
  509.             minutes -= 1;
  510.         }
  511.         while (minutes < 0) {
  512.             minutes += MINUTES_PER_HOUR;
  513.             hours -= 1;
  514.         }
  515.         while (hours < 0) {
  516.             hours += HOURS_PER_DAY;
  517.             days -= 1;
  518.         }

  519.         if (Token.containsTokenWithValue(tokens, M)) {
  520.             while (days < 0) {
  521.                 days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
  522.                 months -= 1;
  523.                 start.add(Calendar.MONTH, 1);
  524.             }

  525.             while (months < 0) {
  526.                 months += 12;
  527.                 years -= 1;
  528.             }

  529.             if (!Token.containsTokenWithValue(tokens, y) && years != 0) {
  530.                 while (years != 0) {
  531.                     months += 12 * years;
  532.                     years = 0;
  533.                 }
  534.             }
  535.         } else {
  536.             // there are no M's in the format string

  537.             if (!Token.containsTokenWithValue(tokens, y)) {
  538.                 int target = end.get(Calendar.YEAR);
  539.                 if (months < 0) {
  540.                     // target is end-year -1
  541.                     target -= 1;
  542.                 }

  543.                 while (start.get(Calendar.YEAR) != target) {
  544.                     days += start.getActualMaximum(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR);

  545.                     // Not sure I grok why this is needed, but the brutal tests show it is
  546.                     if (start instanceof GregorianCalendar &&
  547.                             start.get(Calendar.MONTH) == Calendar.FEBRUARY &&
  548.                             start.get(Calendar.DAY_OF_MONTH) == 29) {
  549.                         days += 1;
  550.                     }

  551.                     start.add(Calendar.YEAR, 1);

  552.                     days += start.get(Calendar.DAY_OF_YEAR);
  553.                 }

  554.                 years = 0;
  555.             }

  556.             while (start.get(Calendar.MONTH) != end.get(Calendar.MONTH)) {
  557.                 days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
  558.                 start.add(Calendar.MONTH, 1);
  559.             }

  560.             months = 0;

  561.             while (days < 0) {
  562.                 days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
  563.                 months -= 1;
  564.                 start.add(Calendar.MONTH, 1);
  565.             }

  566.         }

  567.         // The rest of this code adds in values that
  568.         // aren't requested. This allows the user to ask for the
  569.         // number of months and get the real count and not just 0->11.

  570.         if (!Token.containsTokenWithValue(tokens, d)) {
  571.             hours += HOURS_PER_DAY * days;
  572.             days = 0;
  573.         }
  574.         if (!Token.containsTokenWithValue(tokens, H)) {
  575.             minutes += MINUTES_PER_HOUR * hours;
  576.             hours = 0;
  577.         }
  578.         if (!Token.containsTokenWithValue(tokens, m)) {
  579.             seconds += SECONDS_PER_MINUTES * minutes;
  580.             minutes = 0;
  581.         }
  582.         if (!Token.containsTokenWithValue(tokens, s)) {
  583.             milliseconds += DateUtils.MILLIS_PER_SECOND * seconds;
  584.             seconds = 0;
  585.         }

  586.         return format(tokens, years, months, days, hours, minutes, seconds, milliseconds, padWithZeros);
  587.     }

  588.     /**
  589.      * Formats the time gap as a string.
  590.      *
  591.      * <p>The format used is the ISO 8601 period format.</p>
  592.      *
  593.      * @param startMillis  the start of the duration to format
  594.      * @param endMillis  the end of the duration to format
  595.      * @return the formatted duration, not null
  596.      * @throws IllegalArgumentException if startMillis is greater than endMillis
  597.      */
  598.     public static String formatPeriodISO(final long startMillis, final long endMillis) {
  599.         return formatPeriod(startMillis, endMillis, ISO_EXTENDED_FORMAT_PATTERN, false, TimeZone.getDefault());
  600.     }

  601.     /**
  602.      * Parses a classic date format string into Tokens
  603.      *
  604.      * @param format  the format to parse, not null
  605.      * @return array of Token[]
  606.      */
  607.     static Token[] lexx(final String format) {
  608.         final ArrayList<Token> list = new ArrayList<>(format.length());

  609.         boolean inLiteral = false;
  610.         // Although the buffer is stored in a Token, the Tokens are only
  611.         // used internally, so cannot be accessed by other threads
  612.         StringBuilder buffer = null;
  613.         Token previous = null;
  614.         boolean inOptional = false;
  615.         int optionalIndex = -1;
  616.         for (int i = 0; i < format.length(); i++) {
  617.             final char ch = format.charAt(i);
  618.             if (inLiteral && ch != '\'') {
  619.                 buffer.append(ch); // buffer can't be null if inLiteral is true
  620.                 continue;
  621.             }
  622.             String value = null;
  623.             switch (ch) {
  624.             // TODO: Need to handle escaping of '
  625.             case '[':
  626.                 if (inOptional) {
  627.                     throw new IllegalArgumentException("Nested optional block at index: " + i);
  628.                 }
  629.                 optionalIndex++;
  630.                 inOptional = true;
  631.                 break;
  632.             case ']':
  633.                 if (!inOptional) {
  634.                     throw new IllegalArgumentException("Attempting to close unopened optional block at index: " + i);
  635.                 }
  636.                 inOptional = false;
  637.                 break;
  638.             case '\'':
  639.                 if (inLiteral) {
  640.                     buffer = null;
  641.                     inLiteral = false;
  642.                 } else {
  643.                     buffer = new StringBuilder();
  644.                     list.add(new Token(buffer, inOptional, optionalIndex));
  645.                     inLiteral = true;
  646.                 }
  647.                 break;
  648.             case 'y':
  649.                 value = y;
  650.                 break;
  651.             case 'M':
  652.                 value = M;
  653.                 break;
  654.             case 'd':
  655.                 value = d;
  656.                 break;
  657.             case 'H':
  658.                 value = H;
  659.                 break;
  660.             case 'm':
  661.                 value = m;
  662.                 break;
  663.             case 's':
  664.                 value = s;
  665.                 break;
  666.             case 'S':
  667.                 value = S;
  668.                 break;
  669.             default:
  670.                 if (buffer == null) {
  671.                     buffer = new StringBuilder();
  672.                     list.add(new Token(buffer, inOptional, optionalIndex));
  673.                 }
  674.                 buffer.append(ch);
  675.             }

  676.             if (value != null) {
  677.                 if (previous != null && previous.getValue().equals(value)) {
  678.                     previous.increment();
  679.                 } else {
  680.                     final Token token = new Token(value, inOptional, optionalIndex);
  681.                     list.add(token);
  682.                     previous = token;
  683.                 }
  684.                 buffer = null;
  685.             }
  686.         }
  687.         if (inLiteral) { // i.e. we have not found the end of the literal
  688.             throw new IllegalArgumentException("Unmatched quote in format: " + format);
  689.         }
  690.         if (inOptional) { // i.e. we have not found the end of the literal
  691.             throw new IllegalArgumentException("Unmatched optional in format: " + format);
  692.         }
  693.         return list.toArray(Token.EMPTY_ARRAY);
  694.     }

  695.     /**
  696.      * Converts a {@code long} to a {@link String} with optional
  697.      * zero padding.
  698.      *
  699.      * @param value the value to convert
  700.      * @param padWithZeros whether to pad with zeroes
  701.      * @param count the size to pad to (ignored if {@code padWithZeros} is false)
  702.      * @return the string result
  703.      */
  704.     private static String paddedValue(final long value, final boolean padWithZeros, final int count) {
  705.         final String longString = Long.toString(value);
  706.         return padWithZeros ? StringUtils.leftPad(longString, count, '0') : longString;
  707.     }

  708.     /**
  709.      * DurationFormatUtils instances should NOT be constructed in standard programming.
  710.      *
  711.      * <p>This constructor is public to permit tools that require a JavaBean instance
  712.      * to operate.</p>
  713.      *
  714.      * @deprecated TODO Make private in 4.0.
  715.      */
  716.     @Deprecated
  717.     public DurationFormatUtils() {
  718.         // empty
  719.     }

  720. }