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          * Determines whether a set of tokens contains a duration unit.
104          *
105          * @param tokens set to search.
106          * @param value duration unit to find.
107          * @return boolean {@code true} if contained.
108          */
109         static boolean containsTokenWithValue(final Token[] tokens, final Unit value) {
110             return Stream.of(tokens).anyMatch(token -> token.getValue() == value);
111         }
112 
113         private final Unit value;
114         private final StringBuilder literal;
115         private int count;
116         private final int optionalIndex;
117 
118         /**
119          * Wraps a token around literal text.
120          *
121          * @param literal literal text to wrap, non-null.
122          * @param optional whether the token is optional.
123          * @param optionalIndex The index of the optional token within the pattern.
124          */
125         Token(final StringBuilder literal, final boolean optional, final int optionalIndex) {
126             this.value = null;
127             this.literal = Objects.requireNonNull(literal, "literal");
128             this.count = 1;
129             this.optionalIndex = optional ? optionalIndex : -1;
130         }
131 
132         /**
133          * Wraps a token around a duration unit.
134          *
135          * @param value duration unit to wrap, non-null.
136          * @param optional whether the token is optional.
137          * @param optionalIndex The index of the optional token within the pattern.
138          */
139         Token(final Unit value, final boolean optional, final int optionalIndex) {
140             this.value = Objects.requireNonNull(value, "value");
141             this.literal = null;
142             this.count = 1;
143             this.optionalIndex = optional ? optionalIndex : -1;
144         }
145 
146         /**
147          * Supports equality of this Token to another Token.
148          *
149          * @param obj2 Object to consider equality of.
150          * @return boolean {@code true} if equal.
151          */
152         @Override
153         public boolean equals(final Object obj2) {
154             if (obj2 instanceof Token) {
155                 final Token tok2 = (Token) obj2;
156                 return value == tok2.value && count == tok2.count
157                         && Objects.equals(literal == null ? null : literal.toString(), tok2.literal == null ? null : tok2.literal.toString());
158             }
159             return false;
160         }
161 
162         /**
163          * Gets the current number of values represented.
164          *
165          * @return int number of values represented.
166          */
167         int getCount() {
168             return count;
169         }
170 
171         /**
172          * Gets the duration unit this token represents.
173          *
174          * @return the duration unit, or null for a literal token.
175          */
176         Unit getValue() {
177             return value;
178         }
179 
180         /**
181          * Computes a hash code from the duration unit or literal text, excluding the repetition count.
182          *
183          * @return The hash code for the token.
184          */
185         @Override
186         public int hashCode() {
187             return value != null ? value.hashCode() : literal.toString().hashCode();
188         }
189 
190         /**
191          * Adds another one of the value.
192          */
193         void increment() {
194             count++;
195         }
196 
197         /**
198          * Represents this token as a String.
199          *
200          * @return String representation of the token.
201          */
202         @Override
203         public String toString() {
204             return StringUtils.repeat(value != null ? value.toString() : literal.toString(), count);
205         }
206     }
207 
208     /**
209      * Duration units recognized in format patterns.
210      */
211     enum Unit {
212         YEAR("y"), MONTH("M"), DAY("d"), HOUR("H"), MINUTE("m"), SECOND("s"), MILLISECOND("S");
213 
214         private final String symbol;
215 
216         Unit(final String symbol) {
217             this.symbol = symbol;
218         }
219 
220         @Override
221         public String toString() {
222             return symbol;
223         }
224     }
225 
226     private static final int MINUTES_PER_HOUR = 60;
227 
228     private static final int SECONDS_PER_MINUTES = 60;
229 
230     private static final int HOURS_PER_DAY = 24;
231 
232     /**
233      * Pattern used with {@link FastDateFormat} and {@link SimpleDateFormat} for the ISO 8601 period format used in durations.
234      *
235      * @see org.apache.commons.lang3.time.FastDateFormat
236      * @see java.text.SimpleDateFormat
237      */
238     public static final String ISO_EXTENDED_FORMAT_PATTERN = "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.SSS'S'";
239 
240     /**
241      * The internal method to do the formatting.
242      *
243      * @param tokens  The tokens.
244      * @param years  The number of years.
245      * @param months  The number of months.
246      * @param days  The number of days.
247      * @param hours  The number of hours.
248      * @param minutes  The number of minutes.
249      * @param seconds  The number of seconds.
250      * @param milliseconds  The number of milliseconds.
251      * @param padWithZeros  whether to pad.
252      * @return The formatted string.
253      */
254     static String format(final Token[] tokens, final long years, final long months, final long days, final long hours, final long minutes,
255             final long seconds,
256             final long milliseconds, final boolean padWithZeros) {
257         final StringBuilder buffer = new StringBuilder();
258         boolean lastOutputSeconds = false;
259         boolean lastOutputZero = false;
260         int optionalStart = -1;
261         boolean firstOptionalNonLiteral = false;
262         int optionalIndex = -1;
263         boolean inOptional = false;
264         for (final Token token : tokens) {
265             final Unit unit = token.getValue();
266             final boolean isLiteral = token.literal != null;
267             final int count = token.getCount();
268             if (optionalIndex != token.optionalIndex) {
269               optionalIndex = token.optionalIndex;
270               if (optionalIndex > -1) {
271                 //entering new optional block
272                 optionalStart = buffer.length();
273                 lastOutputZero = false;
274                 inOptional = true;
275                 firstOptionalNonLiteral = false;
276               } else {
277                 //leaving optional block
278                 inOptional = false;
279               }
280             }
281             if (isLiteral) {
282                 if (!inOptional || !lastOutputZero) {
283                     buffer.append(token.literal);
284                 }
285             } else {
286                 final long value;
287                 switch (unit) {
288                 case YEAR:
289                     value = years;
290                     break;
291                 case MONTH:
292                     value = months;
293                     break;
294                 case DAY:
295                     value = days;
296                     break;
297                 case HOUR:
298                     value = hours;
299                     break;
300                 case MINUTE:
301                     value = minutes;
302                     break;
303                 case SECOND:
304                     value = seconds;
305                     break;
306                 case MILLISECOND:
307                     value = milliseconds;
308                     break;
309                 default:
310                     throw new IllegalStateException("Unexpected duration unit: " + unit);
311                 }
312                 lastOutputZero = value == 0;
313                 if (!inOptional || !lastOutputZero) {
314                     if (unit == Unit.MILLISECOND && 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(value, true, width));
318                     } else {
319                         buffer.append(paddedValue(value, padWithZeros, count));
320                     }
321                 }
322                 lastOutputSeconds = unit == Unit.SECOND;
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, Unit.DAY)) {
371             days = milliseconds / DateUtils.MILLIS_PER_DAY;
372             milliseconds -= days * DateUtils.MILLIS_PER_DAY;
373         }
374         if (Token.containsTokenWithValue(tokens, Unit.HOUR)) {
375             hours = milliseconds / DateUtils.MILLIS_PER_HOUR;
376             milliseconds -= hours * DateUtils.MILLIS_PER_HOUR;
377         }
378         if (Token.containsTokenWithValue(tokens, Unit.MINUTE)) {
379             minutes = milliseconds / DateUtils.MILLIS_PER_MINUTE;
380             milliseconds -= minutes * DateUtils.MILLIS_PER_MINUTE;
381         }
382         if (Token.containsTokenWithValue(tokens, Unit.SECOND)) {
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, Unit.YEAR) || Token.containsTokenWithValue(tokens, Unit.MONTH);
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, Unit.YEAR) && years != 0) {
577                 while (years != 0) {
578                     months += 12 * years;
579                     years = 0;
580                 }
581             }
582             if (!Token.containsTokenWithValue(tokens, Unit.MONTH)) {
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, Unit.DAY)) {
597             hours += HOURS_PER_DAY * days;
598             days = 0;
599         }
600         if (!Token.containsTokenWithValue(tokens, Unit.HOUR)) {
601             minutes += MINUTES_PER_HOUR * hours;
602             hours = 0;
603         }
604         if (!Token.containsTokenWithValue(tokens, Unit.MINUTE)) {
605             seconds += SECONDS_PER_MINUTES * minutes;
606             minutes = 0;
607         }
608         if (!Token.containsTokenWithValue(tokens, Unit.SECOND)) {
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             Unit 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 = Unit.YEAR;
694                 break;
695             case 'M':
696                 value = Unit.MONTH;
697                 break;
698             case 'd':
699                 value = Unit.DAY;
700                 break;
701             case 'H':
702                 value = Unit.HOUR;
703                 break;
704             case 'm':
705                 value = Unit.MINUTE;
706                 break;
707             case 's':
708                 value = Unit.SECOND;
709                 break;
710             case 'S':
711                 value = Unit.MILLISECOND;
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() == 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 }