View Javadoc
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    *      https://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  
19  import java.text.SimpleDateFormat;
20  import java.util.ArrayList;
21  import java.util.Calendar;
22  import java.util.Date;
23  import java.util.Objects;
24  import java.util.TimeZone;
25  import java.util.stream.Stream;
26  
27  import org.apache.commons.lang3.StringUtils;
28  import org.apache.commons.lang3.Strings;
29  import org.apache.commons.lang3.Validate;
30  
31  /**
32   * Duration formatting utilities and constants. The following table describes the tokens
33   * used in the pattern language for formatting.
34   *
35   * <table>
36   *  <caption>Pattern Tokens</caption>
37   *  <tr><th>character</th><th>duration element</th></tr>
38   *  <tr><td>y</td><td>years</td></tr>
39   *  <tr><td>M</td><td>months</td></tr>
40   *  <tr><td>d</td><td>days</td></tr>
41   *  <tr><td>H</td><td>hours</td></tr>
42   *  <tr><td>m</td><td>minutes</td></tr>
43   *  <tr><td>s</td><td>seconds</td></tr>
44   *  <tr><td>S</td><td>milliseconds</td></tr>
45   *  <tr><td>'text'</td><td>arbitrary text content</td></tr>
46   *  <tr><td>''</td><td>literal single quote (apostrophe)</td></tr>
47   * </table>
48   *
49   * A literal single quote is represented by a pair of consecutive single quotes ({@code ''}).
50   * <p>
51   * Token values are printed using decimal digits.
52   * A token character can be repeated to ensure that the field occupies a certain minimum
53   * size. Values will be left-padded with 0 unless padding is disabled in the method invocation.
54   * </p>
55   * <p>
56   * Tokens can be marked as optional by surrounding them with brackets [ ]. These tokens will
57   * only be printed if the token value is non-zero. Literals within optional blocks will only be
58   * printed if the preceding non-literal token is non-zero. Leading optional literals will only
59   * be printed if the following non-literal is non-zero.
60   * Multiple optional blocks can be used to group literals with the desired token.
61   * </p>
62   * <p>
63   * Notes on Optional Tokens:
64   * </p>
65   * <p>
66   * <strong>Multiple optional tokens without literals can result in impossible to understand output.</strong>
67   * </p>
68   * <p>
69   * <strong>Patterns where all tokens are optional can produce empty strings.</strong>
70   * </p>
71   * <p>
72   * See the following examples.
73   * </p>
74   *
75   * <table>
76   * <caption>Example Output</caption>
77   * <tr><th>pattern</th><th>Duration.ofDays(1)</th><th>Duration.ofHours(1)</th><th>Duration.ofMinutes(1)</th><th>Duration.ZERO</th></tr>
78   * <tr><td>d'd'H'h'm'm's's'</td><td>1d0h0m0s</td><td>0d1h0m0s</td><td>0d0h1m0s</td><td>0d0h0m0s</td></tr>
79   * <tr><td>d'd'[H'h'm'm']s's'</td><td>1d0s</td><td>0d1h0s</td><td>0d1m0s</td><td>0d0s</td></tr>
80   * <tr><td>[d'd'H'h'm'm']s's'</td><td>1d0s</td><td>1h0s</td><td>1m0s</td><td>0s</td></tr>
81   * <tr><td>[d'd'H'h'm'm's's']</td><td>1d</td><td>1h</td><td>1m</td><td></td></tr>
82   * <tr><td>['{'d'}']HH':'mm</td><td>{1}00:00</td><td>01:00</td><td>00:01</td><td>00:00</td></tr>
83   * <tr><td>['{'dd'}']['&lt;'HH'&gt;']['('mm')']</td><td>{01}</td><td>&lt;01&gt;</td><td>(00)</td><td></td></tr>
84   * <tr><td>[dHms]</td><td>1</td><td>1</td><td>1</td><td></td></tr>
85   * </table>
86   * <p>
87   * <strong>Note: Optional blocks cannot be nested.</strong>
88   * </p>
89   *
90   * @since 2.1
91   */
92  public class DurationFormatUtils {
93  
94      /**
95       * Element that is parsed from the format pattern.
96       */
97      static final class Token {
98  
99          /** Empty array. */
100         private static final Token[] EMPTY_ARRAY = {};
101 
102         /**
103          * Helper method to determine if a set of tokens contain a value
104          *
105          * @param tokens set to search.
106          * @param value to look find.
107          * @return boolean {@code true} if contained.
108          */
109         static boolean containsTokenWithValue(final Token[] tokens, final Object value) {
110             return Stream.of(tokens).anyMatch(token -> token.getValue() == value);
111         }
112 
113         private final CharSequence value;
114         private int count;
115         private int optionalIndex = -1;
116 
117         /**
118          * Wraps a token around a value. A value would be something like a 'Y'.
119          *
120          * @param value value to wrap, non-null.
121          * @param optional whether the token is optional.
122          * @param optionalIndex The index of the optional token within the pattern.
123          */
124         Token(final CharSequence value, final boolean optional, final int optionalIndex) {
125             this.value = Objects.requireNonNull(value, "value");
126             this.count = 1;
127             if (optional) {
128                 this.optionalIndex = optionalIndex;
129             }
130         }
131 
132         /**
133          * Supports equality of this Token to another Token.
134          *
135          * @param obj2 Object to consider equality of.
136          * @return boolean {@code true} if equal.
137          */
138         @Override
139         public boolean equals(final Object obj2) {
140             if (obj2 instanceof Token) {
141                 final Token tok2 = (Token) obj2;
142                 if (this.value.getClass() != tok2.value.getClass() || this.count != tok2.count) {
143                     return false;
144                 }
145                 if (this.value instanceof StringBuilder) {
146                     return this.value.toString().equals(tok2.value.toString());
147                 }
148                 if (this.value instanceof Number) {
149                     return this.value.equals(tok2.value);
150                 }
151                 return this.value == tok2.value;
152             }
153             return false;
154         }
155 
156         /**
157          * Gets the current number of values represented.
158          *
159          * @return int number of values represented.
160          */
161         int getCount() {
162             return count;
163         }
164 
165         /**
166          * Gets the particular value this token represents.
167          *
168          * @return Object value, non-null.
169          */
170         Object getValue() {
171             return value;
172         }
173 
174         /**
175          * Returns a hash code for the token equal to the hash code for the token's value. Thus 'TT' and 'TTTT' will have the same hash code.
176          *
177          * @return The hash code for the token.
178          */
179         @Override
180         public int hashCode() {
181             return this.value.hashCode();
182         }
183 
184         /**
185          * Adds another one of the value.
186          */
187         void increment() {
188             count++;
189         }
190 
191         /**
192          * Represents this token as a String.
193          *
194          * @return String representation of the token.
195          */
196         @Override
197         public String toString() {
198             return StringUtils.repeat(this.value.toString(), this.count);
199         }
200     }
201 
202     private static final int MINUTES_PER_HOUR = 60;
203 
204     private static final int SECONDS_PER_MINUTES = 60;
205 
206     private static final int HOURS_PER_DAY = 24;
207 
208     /**
209      * Pattern used with {@link FastDateFormat} and {@link SimpleDateFormat} for the ISO 8601 period format used in durations.
210      *
211      * @see org.apache.commons.lang3.time.FastDateFormat
212      * @see java.text.SimpleDateFormat
213      */
214     public static final String ISO_EXTENDED_FORMAT_PATTERN = "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.SSS'S'";
215 
216     static final String y = "y";
217 
218     static final String M = "M";
219 
220     static final String d = "d";
221 
222     static final String H = "H";
223 
224     static final String m = "m";
225 
226     static final String s = "s";
227 
228     static final String S = "S";
229 
230     /**
231      * The internal method to do the formatting.
232      *
233      * @param tokens  The tokens.
234      * @param years  The number of years.
235      * @param months  The number of months.
236      * @param days  The number of days.
237      * @param hours  The number of hours.
238      * @param minutes  The number of minutes.
239      * @param seconds  The number of seconds.
240      * @param milliseconds  The number of milliseconds.
241      * @param padWithZeros  whether to pad.
242      * @return The formatted string.
243      */
244     static String format(final Token[] tokens, final long years, final long months, final long days, final long hours, final long minutes,
245             final long seconds,
246             final long milliseconds, final boolean padWithZeros) {
247         final StringBuilder buffer = new StringBuilder();
248         boolean lastOutputSeconds = false;
249         boolean lastOutputZero = false;
250         int optionalStart = -1;
251         boolean firstOptionalNonLiteral = false;
252         int optionalIndex = -1;
253         boolean inOptional = false;
254         for (final Token token : tokens) {
255             final Object value = token.getValue();
256             final boolean isLiteral = value instanceof StringBuilder;
257             final int count = token.getCount();
258             if (optionalIndex != token.optionalIndex) {
259               optionalIndex = token.optionalIndex;
260               if (optionalIndex > -1) {
261                 //entering new optional block
262                 optionalStart = buffer.length();
263                 lastOutputZero = false;
264                 inOptional = true;
265                 firstOptionalNonLiteral = false;
266               } else {
267                 //leaving optional block
268                 inOptional = false;
269               }
270             }
271             if (isLiteral) {
272                 if (!inOptional || !lastOutputZero) {
273                     buffer.append(value.toString());
274                 }
275             } else if (value.equals(y)) {
276                 lastOutputSeconds = false;
277                 lastOutputZero = years == 0;
278                 if (!inOptional || !lastOutputZero) {
279                     buffer.append(paddedValue(years, padWithZeros, count));
280                 }
281             } else if (value.equals(M)) {
282                 lastOutputSeconds = false;
283                 lastOutputZero = months == 0;
284                 if (!inOptional || !lastOutputZero) {
285                     buffer.append(paddedValue(months, padWithZeros, count));
286                 }
287             } else if (value.equals(d)) {
288                 lastOutputSeconds = false;
289                 lastOutputZero = days == 0;
290                 if (!inOptional || !lastOutputZero) {
291                     buffer.append(paddedValue(days, padWithZeros, count));
292                 }
293             } else if (value.equals(H)) {
294                 lastOutputSeconds = false;
295                 lastOutputZero = hours == 0;
296                 if (!inOptional || !lastOutputZero) {
297                     buffer.append(paddedValue(hours, padWithZeros, count));
298                 }
299             } else if (value.equals(m)) {
300                 lastOutputSeconds = false;
301                 lastOutputZero = minutes == 0;
302                 if (!inOptional || !lastOutputZero) {
303                     buffer.append(paddedValue(minutes, padWithZeros, count));
304                 }
305             } else if (value.equals(s)) {
306                 lastOutputSeconds = true;
307                 lastOutputZero = seconds == 0;
308                 if (!inOptional || !lastOutputZero) {
309                     buffer.append(paddedValue(seconds, padWithZeros, count));
310                 }
311             } else if (value.equals(S)) {
312                 lastOutputZero = milliseconds == 0;
313                 if (!inOptional || !lastOutputZero) {
314                     if (lastOutputSeconds) {
315                         // ensure at least 3 digits are displayed even if padding is not selected
316                         final int width = padWithZeros ? Math.max(3, count) : 3;
317                         buffer.append(paddedValue(milliseconds, true, width));
318                     } else {
319                         buffer.append(paddedValue(milliseconds, padWithZeros, count));
320                     }
321                 }
322                 lastOutputSeconds = false;
323             }
324             // as soon as we hit first nonliteral in optional, check for literal prefix
325             if (inOptional && !isLiteral && !firstOptionalNonLiteral) {
326                 firstOptionalNonLiteral = true;
327                 if (lastOutputZero) {
328                     buffer.delete(optionalStart, buffer.length());
329                 }
330             }
331         }
332         return buffer.toString();
333     }
334 
335     /**
336      * Formats the time gap as a string, using the specified format, and padding with zeros.
337      * <p>
338      * This method formats durations using the days and lower fields of the format pattern. Months and larger are not used.
339      * </p>
340      *
341      * @param durationMillis The duration to format.
342      * @param format         The way in which to format the duration, not null.
343      * @return The formatted duration, not null.
344      * @throws IllegalArgumentException Thrown if durationMillis is negative.
345      */
346     public static String formatDuration(final long durationMillis, final String format) {
347         return formatDuration(durationMillis, format, true);
348     }
349 
350     /**
351      * Formats the time gap as a string, using the specified format. Padding the left-hand side of numbers with zeroes is optional.
352      * <p>
353      * This method formats durations using the days and lower fields of the format pattern. Months and larger are not used.
354      * </p>
355      *
356      * @param durationMillis The duration to format.
357      * @param format         The way in which to format the duration, not null.
358      * @param padWithZeros   whether to pad the left-hand side of numbers with 0's.
359      * @return The formatted duration, not null.
360      * @throws IllegalArgumentException Thrown if durationMillis is negative.
361      */
362     public static String formatDuration(final long durationMillis, final String format, final boolean padWithZeros) {
363         Validate.inclusiveBetween(0, Long.MAX_VALUE, durationMillis, "durationMillis must not be negative");
364         final Token[] tokens = lexx(format);
365         long days = 0;
366         long hours = 0;
367         long minutes = 0;
368         long seconds = 0;
369         long milliseconds = durationMillis;
370         if (Token.containsTokenWithValue(tokens, d)) {
371             days = milliseconds / DateUtils.MILLIS_PER_DAY;
372             milliseconds -= days * DateUtils.MILLIS_PER_DAY;
373         }
374         if (Token.containsTokenWithValue(tokens, H)) {
375             hours = milliseconds / DateUtils.MILLIS_PER_HOUR;
376             milliseconds -= hours * DateUtils.MILLIS_PER_HOUR;
377         }
378         if (Token.containsTokenWithValue(tokens, m)) {
379             minutes = milliseconds / DateUtils.MILLIS_PER_MINUTE;
380             milliseconds -= minutes * DateUtils.MILLIS_PER_MINUTE;
381         }
382         if (Token.containsTokenWithValue(tokens, s)) {
383             seconds = milliseconds / DateUtils.MILLIS_PER_SECOND;
384             milliseconds -= seconds * DateUtils.MILLIS_PER_SECOND;
385         }
386         return format(tokens, 0, 0, days, hours, minutes, seconds, milliseconds, padWithZeros);
387     }
388 
389     /**
390      * Formats the time gap as a string.
391      * <p>
392      * The format used is ISO 8601-like: {@code HH:mm:ss.SSS}.
393      * </p>
394      *
395      * @param durationMillis The duration to format.
396      * @return The formatted duration, not null.
397      * @throws IllegalArgumentException Thrown if durationMillis is negative.
398      */
399     public static String formatDurationHMS(final long durationMillis) {
400         return formatDuration(durationMillis, "HH:mm:ss.SSS");
401     }
402 
403     /**
404      * Formats the time gap as a string.
405      * <p>
406      * The format used is the ISO 8601 period format.
407      * </p>
408      * <p>
409      * This method formats durations using the days and lower fields of the ISO format pattern, such as P7D6TH5M4.321S.
410      * </p>
411      *
412      * @param durationMillis The duration to format.
413      * @return The formatted duration, not null.
414      * @throws IllegalArgumentException Thrown if durationMillis is negative.
415      */
416     public static String formatDurationISO(final long durationMillis) {
417         return formatDuration(durationMillis, ISO_EXTENDED_FORMAT_PATTERN, false);
418     }
419 
420     /**
421      * Formats an elapsed time into a pluralization correct string.
422      * <p>
423      * This method formats durations using the days and lower fields of the format pattern. Months and larger are not used.
424      * </p>
425      *
426      * @param durationMillis               The elapsed time to report in milliseconds.
427      * @param suppressLeadingZeroElements  suppresses leading 0 elements.
428      * @param suppressTrailingZeroElements suppresses trailing 0 elements.
429      * @return The formatted text in days/hours/minutes/seconds, not null.
430      * @throws IllegalArgumentException Thrown if durationMillis is negative.
431      */
432     public static String formatDurationWords(final long durationMillis, final boolean suppressLeadingZeroElements, final boolean suppressTrailingZeroElements) {
433         // This method is generally replaceable by the format method, but
434         // there are a series of tweaks and special cases that require
435         // trickery to replicate.
436         String duration = formatDuration(durationMillis, "d' days 'H' hours 'm' minutes 's' seconds'");
437         if (suppressLeadingZeroElements) {
438             // this is a temporary marker on the front. Like ^ in regexp.
439             duration = " " + duration;
440             final String text = duration;
441             String tmp = Strings.CS.replaceOnce(text, " 0 days", StringUtils.EMPTY);
442             if (tmp.length() != duration.length()) {
443                 duration = tmp;
444                 final String text1 = duration;
445                 tmp = Strings.CS.replaceOnce(text1, " 0 hours", StringUtils.EMPTY);
446                 if (tmp.length() != duration.length()) {
447                     duration = tmp;
448                     final String text2 = duration;
449                     tmp = Strings.CS.replaceOnce(text2, " 0 minutes", StringUtils.EMPTY);
450                     duration = tmp;
451                 }
452             }
453             if (!duration.isEmpty()) {
454                 // strip the space off again
455                 duration = duration.substring(1);
456             }
457         }
458         if (suppressTrailingZeroElements) {
459             final String text = duration;
460             String tmp = Strings.CS.replaceOnce(text, " 0 seconds", StringUtils.EMPTY);
461             if (tmp.length() != duration.length()) {
462                 duration = tmp;
463                 final String text1 = duration;
464                 tmp = Strings.CS.replaceOnce(text1, " 0 minutes", StringUtils.EMPTY);
465                 if (tmp.length() != duration.length()) {
466                     duration = tmp;
467                     final String text2 = duration;
468                     tmp = Strings.CS.replaceOnce(text2, " 0 hours", StringUtils.EMPTY);
469                     if (tmp.length() != duration.length()) {
470                         final String text3 = tmp;
471                         duration = Strings.CS.replaceOnce(text3, " 0 days", StringUtils.EMPTY);
472                     }
473                 }
474             }
475         }
476         // handle plurals
477         duration = " " + duration;
478         final String text = duration;
479         duration = Strings.CS.replaceOnce(text, " 1 seconds", " 1 second");
480         final String text1 = duration;
481         duration = Strings.CS.replaceOnce(text1, " 1 minutes", " 1 minute");
482         final String text2 = duration;
483         duration = Strings.CS.replaceOnce(text2, " 1 hours", " 1 hour");
484         final String text3 = duration;
485         duration = Strings.CS.replaceOnce(text3, " 1 days", " 1 day");
486         return duration.trim();
487     }
488 
489     /**
490      * Formats the time gap as a string, using the specified format. Padding the left-hand side of numbers with zeroes is optional.
491      *
492      * @param startMillis The start of the duration.
493      * @param endMillis   The end of the duration.
494      * @param format      The way in which to format the duration, not null.
495      * @return The formatted duration, not null.
496      * @throws IllegalArgumentException Thrown if startMillis is greater than endMillis.
497      */
498     public static String formatPeriod(final long startMillis, final long endMillis, final String format) {
499         return formatPeriod(startMillis, endMillis, format, true, TimeZone.getDefault());
500     }
501 
502     /**
503      * <p>
504      * Formats the time gap as a string, using the specified format. Padding the left-hand side of numbers with zeroes is optional and the time zone may be
505      * specified.
506      * <p>
507      * When calculating the difference between months/days, it chooses to calculate months first, borrowing the length of the month in which the period starts
508      * when the number of days would otherwise be negative. So when working out the number of months and days between January 15th and March 10th, it chooses
509      * 1 month and 26 days gained by choosing March -&gt; February = 1 month and then calculating days backwards, and not the 1 month and 23 days gained by
510      * choosing January-&gt;February = 1 month and then calculating days forwards, as computed by {@link java.time.Period#between}.
511      * </p>
512      * <p>
513      * For more control, the <a href="https://www.joda.org/joda-time/">Joda-Time</a> library is recommended.
514      * </p>
515      *
516      * @param startMillis  The start of the duration.
517      * @param endMillis    The end of the duration.
518      * @param format       The way in which to format the duration, not null.
519      * @param padWithZeros whether to pad the left-hand side of numbers with 0's.
520      * @param timezone     The millis are defined in.
521      * @return The formatted duration, not null.
522      * @throws IllegalArgumentException Thrown if startMillis is greater than endMillis.
523      */
524     public static String formatPeriod(final long startMillis, final long endMillis, final String format, final boolean padWithZeros,
525             final TimeZone timezone) {
526         Validate.isTrue(startMillis <= endMillis, "startMillis must not be greater than endMillis");
527         // Used to optimize for differences under 28 days and
528         // called formatDuration(millis, format); however this did not work
529         // over leap years.
530         // TODO: Compare performance to see if anything was lost by
531         // losing this optimization.
532         final Token[] tokens = lexx(format);
533         // time zones get funky around 0, so normalizing everything to GMT
534         // stops the hours being off
535         final Calendar start = Calendar.getInstance(timezone);
536         start.setTime(new Date(startMillis));
537         final Calendar end = Calendar.getInstance(timezone);
538         end.setTime(new Date(endMillis));
539         // initial estimates
540         long milliseconds = end.get(Calendar.MILLISECOND) - start.get(Calendar.MILLISECOND);
541         long seconds = end.get(Calendar.SECOND) - start.get(Calendar.SECOND);
542         long minutes = end.get(Calendar.MINUTE) - start.get(Calendar.MINUTE);
543         long hours = end.get(Calendar.HOUR_OF_DAY) - start.get(Calendar.HOUR_OF_DAY);
544         final boolean calendarUnits = Token.containsTokenWithValue(tokens, y) || Token.containsTokenWithValue(tokens, M);
545         // Without years or months, count local dates directly instead of visiting every intervening month.
546         long days = calendarUnits ? end.get(Calendar.DAY_OF_MONTH) - start.get(Calendar.DAY_OF_MONTH) : localEpochDay(end) - localEpochDay(start);
547         long months = end.get(Calendar.MONTH) - start.get(Calendar.MONTH);
548         long years = end.get(Calendar.YEAR) - start.get(Calendar.YEAR);
549         // each initial estimate is adjusted in case it is under 0
550         while (milliseconds < 0) {
551             milliseconds += DateUtils.MILLIS_PER_SECOND;
552             seconds -= 1;
553         }
554         while (seconds < 0) {
555             seconds += SECONDS_PER_MINUTES;
556             minutes -= 1;
557         }
558         while (minutes < 0) {
559             minutes += MINUTES_PER_HOUR;
560             hours -= 1;
561         }
562         while (hours < 0) {
563             hours += HOURS_PER_DAY;
564             days -= 1;
565         }
566         if (calendarUnits) {
567             while (days < 0) {
568                 days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
569                 months -= 1;
570                 start.add(Calendar.MONTH, 1);
571             }
572             while (months < 0) {
573                 months += 12;
574                 years -= 1;
575             }
576             if (!Token.containsTokenWithValue(tokens, y) && years != 0) {
577                 while (years != 0) {
578                     months += 12 * years;
579                     years = 0;
580                 }
581             }
582             if (!Token.containsTokenWithValue(tokens, M)) {
583                 while (months > 0) {
584                     days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
585                     months -= 1;
586                     start.add(Calendar.MONTH, 1);
587                 }
588             }
589         } else {
590             months = 0;
591             years = 0;
592         }
593         // The rest of this code adds in values that
594         // aren't requested. This allows the user to ask for the
595         // number of months and get the real count and not just 0->11.
596         if (!Token.containsTokenWithValue(tokens, d)) {
597             hours += HOURS_PER_DAY * days;
598             days = 0;
599         }
600         if (!Token.containsTokenWithValue(tokens, H)) {
601             minutes += MINUTES_PER_HOUR * hours;
602             hours = 0;
603         }
604         if (!Token.containsTokenWithValue(tokens, m)) {
605             seconds += SECONDS_PER_MINUTES * minutes;
606             minutes = 0;
607         }
608         if (!Token.containsTokenWithValue(tokens, s)) {
609             milliseconds += DateUtils.MILLIS_PER_SECOND * seconds;
610             seconds = 0;
611         }
612         return format(tokens, years, months, days, hours, minutes, seconds, milliseconds, padWithZeros);
613     }
614 
615     /**
616      * Formats the time gap as a string.
617      * <p>
618      * The format used is the ISO 8601 period format.
619      * </p>
620      *
621      * @param startMillis The start of the duration to format.
622      * @param endMillis   The end of the duration to format.
623      * @return The formatted duration, not null.
624      * @throws IllegalArgumentException Thrown if startMillis is greater than endMillis.
625      */
626     public static String formatPeriodISO(final long startMillis, final long endMillis) {
627         return formatPeriod(startMillis, endMillis, ISO_EXTENDED_FORMAT_PATTERN, false, TimeZone.getDefault());
628     }
629 
630     /**
631      * Parses a classic date format string into Tokens
632      *
633      * @param format  The format to parse, not null.
634      * @return array of Token[].
635      */
636     static Token[] lexx(final String format) {
637         final ArrayList<Token> list = new ArrayList<>(format.length());
638         boolean inLiteral = false;
639         // Although the buffer is stored in a Token, the Tokens are only
640         // used internally, so cannot be accessed by other threads
641         StringBuilder buffer = null;
642         Token previous = null;
643         boolean inOptional = false;
644         int optionalIndex = -1;
645         for (int i = 0; i < format.length(); i++) {
646             final char ch = format.charAt(i);
647             if (inLiteral && ch != '\'') {
648                 buffer.append(ch); // buffer can't be null if inLiteral is true
649                 continue;
650             }
651             String value = null;
652             switch (ch) {
653             case '[':
654                 if (inOptional) {
655                     throw new IllegalArgumentException("Nested optional block at index: " + i);
656                 }
657                 optionalIndex++;
658                 inOptional = true;
659                 previous = null;
660                 break;
661             case ']':
662                 if (!inOptional) {
663                     throw new IllegalArgumentException("Attempting to close unopened optional block at index: " + i);
664                 }
665                 inOptional = false;
666                 previous = null;
667                 break;
668             case '\'':
669                 if (inLiteral) {
670                     if (i + 1 < format.length() && format.charAt(i + 1) == '\'') {
671                         // escaped quote '' ? append literal apostrophe, stay in literal
672                         buffer.append('\'');
673                         i++;
674                     } else {
675                         // end of literal
676                         buffer = null;
677                         inLiteral = false;
678                     }
679                 } else if (i + 1 < format.length() && format.charAt(i + 1) == '\'') {
680                     // standalone '' outside a literal ? emit a single apostrophe
681                     buffer = new StringBuilder("'");
682                     list.add(new Token(buffer, inOptional, optionalIndex));
683                     buffer = null;
684                     i++;
685                 } else {
686                     buffer = new StringBuilder();
687                     list.add(new Token(buffer, inOptional, optionalIndex));
688                     inLiteral = true;
689                 }
690                 previous = null;
691                 break;
692             case 'y':
693                 value = y;
694                 break;
695             case 'M':
696                 value = M;
697                 break;
698             case 'd':
699                 value = d;
700                 break;
701             case 'H':
702                 value = H;
703                 break;
704             case 'm':
705                 value = m;
706                 break;
707             case 's':
708                 value = s;
709                 break;
710             case 'S':
711                 value = S;
712                 break;
713             default:
714                 if (buffer == null) {
715                     buffer = new StringBuilder();
716                     list.add(new Token(buffer, inOptional, optionalIndex));
717                 }
718                 buffer.append(ch);
719                 previous = null;
720             }
721             if (value != null) {
722                 if (previous != null && previous.getValue().equals(value)) {
723                     previous.increment();
724                 } else {
725                     final Token token = new Token(value, inOptional, optionalIndex);
726                     list.add(token);
727                     previous = token;
728                 }
729                 buffer = null;
730             }
731         }
732         if (inLiteral) { // i.e. we have not found the end of the literal
733             throw new IllegalArgumentException("Unmatched quote in format: " + format);
734         }
735         if (inOptional) { // i.e. we have not found the end of the literal
736             throw new IllegalArgumentException("Unmatched optional in format: " + format);
737         }
738         return list.toArray(Token.EMPTY_ARRAY);
739     }
740 
741     /**
742      * Computes the local epoch day without overflowing at either end of the millisecond range.
743      *
744      * @param calendar the calendar to convert.
745      * @return the local epoch day.
746      */
747     private static long localEpochDay(final Calendar calendar) {
748         final long millis = calendar.getTimeInMillis();
749         final long offset = (long) calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
750         return Math.floorDiv(millis, DateUtils.MILLIS_PER_DAY)
751                 + Math.floorDiv(Math.floorMod(millis, DateUtils.MILLIS_PER_DAY) + offset, DateUtils.MILLIS_PER_DAY);
752     }
753 
754     /**
755      * Converts a {@code long} to a {@link String} with optional zero padding.
756      *
757      * @param value        The value to convert.
758      * @param padWithZeros whether to pad with zeroes.
759      * @param count        The size to pad to (ignored if {@code padWithZeros} is false).
760      * @return The string result.
761      */
762     private static String paddedValue(final long value, final boolean padWithZeros, final int count) {
763         final String longString = Long.toString(value);
764         return padWithZeros ? StringUtils.leftPad(longString, count, '0') : longString;
765     }
766 
767     /**
768      * DurationFormatUtils instances should NOT be constructed in standard programming.
769      * <p>
770      * This constructor is public to permit tools that require a JavaBean instance to operate.
771      * </p>
772      *
773      * @deprecated TODO Make private in 4.0.
774      */
775     @Deprecated
776     public DurationFormatUtils() {
777         // empty
778     }
779 
780 }