1 /* 2 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /* 27 * This file is available under and governed by the GNU General Public 28 * License version 2 only, as published by the Free Software Foundation. 29 * However, the following notice accompanied the original version of this 30 * file: 31 * 32 * Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos 33 * 34 * All rights reserved. 35 * 36 * Redistribution and use in source and binary forms, with or without 37 * modification, are permitted provided that the following conditions are met: 38 * 39 * * Redistributions of source code must retain the above copyright notice, 40 * this list of conditions and the following disclaimer. 41 * 42 * * Redistributions in binary form must reproduce the above copyright notice, 43 * this list of conditions and the following disclaimer in the documentation 44 * and/or other materials provided with the distribution. 45 * 46 * * Neither the name of JSR-310 nor the names of its contributors 47 * may be used to endorse or promote products derived from this software 48 * without specific prior written permission. 49 * 50 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 51 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 52 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 53 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 54 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 55 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 56 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 57 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 58 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 59 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 60 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 61 */ 62 package java.time.format; 63 64 import static java.time.temporal.ChronoField.DAY_OF_MONTH; 65 import static java.time.temporal.ChronoField.HOUR_OF_DAY; 66 import static java.time.temporal.ChronoField.INSTANT_SECONDS; 67 import static java.time.temporal.ChronoField.MINUTE_OF_HOUR; 68 import static java.time.temporal.ChronoField.MONTH_OF_YEAR; 69 import static java.time.temporal.ChronoField.NANO_OF_SECOND; 70 import static java.time.temporal.ChronoField.OFFSET_SECONDS; 71 import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; 72 import static java.time.temporal.ChronoField.YEAR; 73 import static java.time.temporal.ChronoField.ERA; 74 75 import java.lang.ref.SoftReference; 76 import java.math.BigDecimal; 77 import java.math.BigInteger; 78 import java.math.RoundingMode; 79 import java.text.ParsePosition; 80 import java.time.DateTimeException; 81 import java.time.Instant; 82 import java.time.LocalDate; 83 import java.time.LocalDateTime; 84 import java.time.ZoneId; 85 import java.time.ZoneOffset; 86 import java.time.chrono.ChronoLocalDate; 87 import java.time.chrono.Chronology; 88 import java.time.chrono.Era; 89 import java.time.chrono.IsoChronology; 90 import java.time.format.DateTimeTextProvider.LocaleStore; 91 import java.time.temporal.ChronoField; 92 import java.time.temporal.IsoFields; 93 import java.time.temporal.TemporalAccessor; 94 import java.time.temporal.TemporalField; 95 import java.time.temporal.TemporalQueries; 96 import java.time.temporal.TemporalQuery; 97 import java.time.temporal.ValueRange; 98 import java.time.temporal.WeekFields; 99 import java.time.zone.ZoneRulesProvider; 100 import java.util.AbstractMap.SimpleImmutableEntry; 101 import java.util.ArrayList; 102 import java.util.Arrays; 103 import java.util.Collections; 104 import java.util.Comparator; 105 import java.util.HashMap; 106 import java.util.HashSet; 107 import java.util.Iterator; 108 import java.util.LinkedHashMap; 109 import java.util.List; 110 import java.util.Locale; 111 import java.util.Map; 112 import java.util.Map.Entry; 113 import java.util.Objects; 114 import java.util.Set; 115 import java.util.TimeZone; 116 import java.util.concurrent.ConcurrentHashMap; 117 import java.util.concurrent.ConcurrentMap; 118 119 import sun.util.locale.provider.LocaleProviderAdapter; 120 import sun.util.locale.provider.LocaleResources; 121 import sun.util.locale.provider.TimeZoneNameUtility; 122 123 /** 124 * Builder to create date-time formatters. 125 * <p> 126 * This allows a {@code DateTimeFormatter} to be created. 127 * All date-time formatters are created ultimately using this builder. 128 * <p> 129 * The basic elements of date-time can all be added: 130 * <ul> 131 * <li>Value - a numeric value</li> 132 * <li>Fraction - a fractional value including the decimal place. Always use this when 133 * outputting fractions to ensure that the fraction is parsed correctly</li> 134 * <li>Text - the textual equivalent for the value</li> 135 * <li>OffsetId/Offset - the {@linkplain ZoneOffset zone offset}</li> 136 * <li>ZoneId - the {@linkplain ZoneId time-zone} id</li> 137 * <li>ZoneText - the name of the time-zone</li> 138 * <li>ChronologyId - the {@linkplain Chronology chronology} id</li> 139 * <li>ChronologyText - the name of the chronology</li> 140 * <li>Literal - a text literal</li> 141 * <li>Nested and Optional - formats can be nested or made optional</li> 142 * </ul> 143 * In addition, any of the elements may be decorated by padding, either with spaces or any other character. 144 * <p> 145 * Finally, a shorthand pattern, mostly compatible with {@code java.text.SimpleDateFormat SimpleDateFormat} 146 * can be used, see {@link #appendPattern(String)}. 147 * In practice, this simply parses the pattern and calls other methods on the builder. 148 * 149 * @implSpec 150 * This class is a mutable builder intended for use from a single thread. 151 * 152 * @since 1.8 153 */ 154 public final class DateTimeFormatterBuilder { 155 156 /** 157 * Query for a time-zone that is region-only. 158 */ 159 private static final TemporalQuery<ZoneId> QUERY_REGION_ONLY = (temporal) -> { 160 ZoneId zone = temporal.query(TemporalQueries.zoneId()); 161 return (zone != null && zone instanceof ZoneOffset == false ? zone : null); 162 }; 163 164 /** 165 * The currently active builder, used by the outermost builder. 166 */ 167 private DateTimeFormatterBuilder active = this; 168 /** 169 * The parent builder, null for the outermost builder. 170 */ 171 private final DateTimeFormatterBuilder parent; 172 /** 173 * The list of printers that will be used. 174 */ 175 private final List<DateTimePrinterParser> printerParsers = new ArrayList<>(); 176 /** 177 * Whether this builder produces an optional formatter. 178 */ 179 private final boolean optional; 180 /** 181 * The width to pad the next field to. 182 */ 183 private int padNextWidth; 184 /** 185 * The character to pad the next field with. 186 */ 187 private char padNextChar; 188 /** 189 * The index of the last variable width value parser. 190 */ 191 private int valueParserIndex = -1; 192 193 /** 194 * Gets the formatting pattern for date and time styles for a locale and chronology. 195 * The locale and chronology are used to lookup the locale specific format 196 * for the requested dateStyle and/or timeStyle. 197 * 198 * @param dateStyle the FormatStyle for the date, null for time-only pattern 199 * @param timeStyle the FormatStyle for the time, null for date-only pattern 200 * @param chrono the Chronology, non-null 201 * @param locale the locale, non-null 202 * @return the locale and Chronology specific formatting pattern 203 * @throws IllegalArgumentException if both dateStyle and timeStyle are null 204 */ 205 public static String getLocalizedDateTimePattern(FormatStyle dateStyle, FormatStyle timeStyle, 206 Chronology chrono, Locale locale) { 207 Objects.requireNonNull(locale, "locale"); 208 Objects.requireNonNull(chrono, "chrono"); 209 if (dateStyle == null && timeStyle == null) { 210 throw new IllegalArgumentException("Either dateStyle or timeStyle must be non-null"); 211 } 212 LocaleResources lr = LocaleProviderAdapter.getResourceBundleBased().getLocaleResources(locale); 213 String pattern = lr.getJavaTimeDateTimePattern( 214 convertStyle(timeStyle), convertStyle(dateStyle), chrono.getCalendarType()); 215 return pattern; 216 } 217 218 /** 219 * Converts the given FormatStyle to the java.text.DateFormat style. 220 * 221 * @param style the FormatStyle style 222 * @return the int style, or -1 if style is null, indicating un-required 223 */ 224 private static int convertStyle(FormatStyle style) { 225 if (style == null) { 226 return -1; 227 } 228 return style.ordinal(); // indices happen to align 229 } 230 231 /** 232 * Constructs a new instance of the builder. 233 */ 234 public DateTimeFormatterBuilder() { 235 super(); 236 parent = null; 237 optional = false; 238 } 239 240 /** 241 * Constructs a new instance of the builder. 242 * 243 * @param parent the parent builder, not null 244 * @param optional whether the formatter is optional, not null 245 */ 246 private DateTimeFormatterBuilder(DateTimeFormatterBuilder parent, boolean optional) { 247 super(); 248 this.parent = parent; 249 this.optional = optional; 250 } 251 252 //----------------------------------------------------------------------- 253 /** 254 * Changes the parse style to be case sensitive for the remainder of the formatter. 255 * <p> 256 * Parsing can be case sensitive or insensitive - by default it is case sensitive. 257 * This method allows the case sensitivity setting of parsing to be changed. 258 * <p> 259 * Calling this method changes the state of the builder such that all 260 * subsequent builder method calls will parse text in case sensitive mode. 261 * See {@link #parseCaseInsensitive} for the opposite setting. 262 * The parse case sensitive/insensitive methods may be called at any point 263 * in the builder, thus the parser can swap between case parsing modes 264 * multiple times during the parse. 265 * <p> 266 * Since the default is case sensitive, this method should only be used after 267 * a previous call to {@code #parseCaseInsensitive}. 268 * 269 * @return this, for chaining, not null 270 */ 271 public DateTimeFormatterBuilder parseCaseSensitive() { 272 appendInternal(SettingsParser.SENSITIVE); 273 return this; 274 } 275 276 /** 277 * Changes the parse style to be case insensitive for the remainder of the formatter. 278 * <p> 279 * Parsing can be case sensitive or insensitive - by default it is case sensitive. 280 * This method allows the case sensitivity setting of parsing to be changed. 281 * <p> 282 * Calling this method changes the state of the builder such that all 283 * subsequent builder method calls will parse text in case insensitive mode. 284 * See {@link #parseCaseSensitive()} for the opposite setting. 285 * The parse case sensitive/insensitive methods may be called at any point 286 * in the builder, thus the parser can swap between case parsing modes 287 * multiple times during the parse. 288 * 289 * @return this, for chaining, not null 290 */ 291 public DateTimeFormatterBuilder parseCaseInsensitive() { 292 appendInternal(SettingsParser.INSENSITIVE); 293 return this; 294 } 295 296 //----------------------------------------------------------------------- 297 /** 298 * Changes the parse style to be strict for the remainder of the formatter. 299 * <p> 300 * Parsing can be strict or lenient - by default its strict. 301 * This controls the degree of flexibility in matching the text and sign styles. 302 * <p> 303 * When used, this method changes the parsing to be strict from this point onwards. 304 * As strict is the default, this is normally only needed after calling {@link #parseLenient()}. 305 * The change will remain in force until the end of the formatter that is eventually 306 * constructed or until {@code parseLenient} is called. 307 * 308 * @return this, for chaining, not null 309 */ 310 public DateTimeFormatterBuilder parseStrict() { 311 appendInternal(SettingsParser.STRICT); 312 return this; 313 } 314 315 /** 316 * Changes the parse style to be lenient for the remainder of the formatter. 317 * Note that case sensitivity is set separately to this method. 318 * <p> 319 * Parsing can be strict or lenient - by default its strict. 320 * This controls the degree of flexibility in matching the text and sign styles. 321 * Applications calling this method should typically also call {@link #parseCaseInsensitive()}. 322 * <p> 323 * When used, this method changes the parsing to be lenient from this point onwards. 324 * The change will remain in force until the end of the formatter that is eventually 325 * constructed or until {@code parseStrict} is called. 326 * 327 * @return this, for chaining, not null 328 */ 329 public DateTimeFormatterBuilder parseLenient() { 330 appendInternal(SettingsParser.LENIENT); 331 return this; 332 } 333 334 //----------------------------------------------------------------------- 335 /** 336 * Appends a default value for a field to the formatter for use in parsing. 337 * <p> 338 * This appends an instruction to the builder to inject a default value 339 * into the parsed result. This is especially useful in conjunction with 340 * optional parts of the formatter. 341 * <p> 342 * For example, consider a formatter that parses the year, followed by 343 * an optional month, with a further optional day-of-month. Using such a 344 * formatter would require the calling code to check whether a full date, 345 * year-month or just a year had been parsed. This method can be used to 346 * default the month and day-of-month to a sensible value, such as the 347 * first of the month, allowing the calling code to always get a date. 348 * <p> 349 * During formatting, this method has no effect. 350 * <p> 351 * During parsing, the current state of the parse is inspected. 352 * If the specified field has no associated value, because it has not been 353 * parsed successfully at that point, then the specified value is injected 354 * into the parse result. Injection is immediate, thus the field-value pair 355 * will be visible to any subsequent elements in the formatter. 356 * As such, this method is normally called at the end of the builder. 357 * 358 * @param field the field to default the value of, not null 359 * @param value the value to default the field to 360 * @return this, for chaining, not null 361 */ 362 public DateTimeFormatterBuilder parseDefaulting(TemporalField field, long value) { 363 Objects.requireNonNull(field, "field"); 364 appendInternal(new DefaultValueParser(field, value)); 365 return this; 366 } 367 368 //----------------------------------------------------------------------- 369 /** 370 * Appends the value of a date-time field to the formatter using a normal 371 * output style. 372 * <p> 373 * The value of the field will be output during a format. 374 * If the value cannot be obtained then an exception will be thrown. 375 * <p> 376 * The value will be printed as per the normal format of an integer value. 377 * Only negative numbers will be signed. No padding will be added. 378 * <p> 379 * The parser for a variable width value such as this normally behaves greedily, 380 * requiring one digit, but accepting as many digits as possible. 381 * This behavior can be affected by 'adjacent value parsing'. 382 * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details. 383 * 384 * @param field the field to append, not null 385 * @return this, for chaining, not null 386 */ 387 public DateTimeFormatterBuilder appendValue(TemporalField field) { 388 Objects.requireNonNull(field, "field"); 389 appendValue(new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL)); 390 return this; 391 } 392 393 /** 394 * Appends the value of a date-time field to the formatter using a fixed 395 * width, zero-padded approach. 396 * <p> 397 * The value of the field will be output during a format. 398 * If the value cannot be obtained then an exception will be thrown. 399 * <p> 400 * The value will be zero-padded on the left. If the size of the value 401 * means that it cannot be printed within the width then an exception is thrown. 402 * If the value of the field is negative then an exception is thrown during formatting. 403 * <p> 404 * This method supports a special technique of parsing known as 'adjacent value parsing'. 405 * This technique solves the problem where a value, variable or fixed width, is followed by one or more 406 * fixed length values. The standard parser is greedy, and thus it would normally 407 * steal the digits that are needed by the fixed width value parsers that follow the 408 * variable width one. 409 * <p> 410 * No action is required to initiate 'adjacent value parsing'. 411 * When a call to {@code appendValue} is made, the builder 412 * enters adjacent value parsing setup mode. If the immediately subsequent method 413 * call or calls on the same builder are for a fixed width value, then the parser will reserve 414 * space so that the fixed width values can be parsed. 415 * <p> 416 * For example, consider {@code builder.appendValue(YEAR).appendValue(MONTH_OF_YEAR, 2);} 417 * The year is a variable width parse of between 1 and 19 digits. 418 * The month is a fixed width parse of 2 digits. 419 * Because these were appended to the same builder immediately after one another, 420 * the year parser will reserve two digits for the month to parse. 421 * Thus, the text '201106' will correctly parse to a year of 2011 and a month of 6. 422 * Without adjacent value parsing, the year would greedily parse all six digits and leave 423 * nothing for the month. 424 * <p> 425 * Adjacent value parsing applies to each set of fixed width not-negative values in the parser 426 * that immediately follow any kind of value, variable or fixed width. 427 * Calling any other append method will end the setup of adjacent value parsing. 428 * Thus, in the unlikely event that you need to avoid adjacent value parsing behavior, 429 * simply add the {@code appendValue} to another {@code DateTimeFormatterBuilder} 430 * and add that to this builder. 431 * <p> 432 * If adjacent parsing is active, then parsing must match exactly the specified 433 * number of digits in both strict and lenient modes. 434 * In addition, no positive or negative sign is permitted. 435 * 436 * @param field the field to append, not null 437 * @param width the width of the printed field, from 1 to 19 438 * @return this, for chaining, not null 439 * @throws IllegalArgumentException if the width is invalid 440 */ 441 public DateTimeFormatterBuilder appendValue(TemporalField field, int width) { 442 Objects.requireNonNull(field, "field"); 443 if (width < 1 || width > 19) { 444 throw new IllegalArgumentException("The width must be from 1 to 19 inclusive but was " + width); 445 } 446 NumberPrinterParser pp = new NumberPrinterParser(field, width, width, SignStyle.NOT_NEGATIVE); 447 appendValue(pp); 448 return this; 449 } 450 451 /** 452 * Appends the value of a date-time field to the formatter providing full 453 * control over formatting. 454 * <p> 455 * The value of the field will be output during a format. 456 * If the value cannot be obtained then an exception will be thrown. 457 * <p> 458 * This method provides full control of the numeric formatting, including 459 * zero-padding and the positive/negative sign. 460 * <p> 461 * The parser for a variable width value such as this normally behaves greedily, 462 * accepting as many digits as possible. 463 * This behavior can be affected by 'adjacent value parsing'. 464 * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details. 465 * <p> 466 * In strict parsing mode, the minimum number of parsed digits is {@code minWidth} 467 * and the maximum is {@code maxWidth}. 468 * In lenient parsing mode, the minimum number of parsed digits is one 469 * and the maximum is 19 (except as limited by adjacent value parsing). 470 * <p> 471 * If this method is invoked with equal minimum and maximum widths and a sign style of 472 * {@code NOT_NEGATIVE} then it delegates to {@code appendValue(TemporalField,int)}. 473 * In this scenario, the formatting and parsing behavior described there occur. 474 * 475 * @param field the field to append, not null 476 * @param minWidth the minimum field width of the printed field, from 1 to 19 477 * @param maxWidth the maximum field width of the printed field, from 1 to 19 478 * @param signStyle the positive/negative output style, not null 479 * @return this, for chaining, not null 480 * @throws IllegalArgumentException if the widths are invalid 481 */ 482 public DateTimeFormatterBuilder appendValue( 483 TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) { 484 if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) { 485 return appendValue(field, maxWidth); 486 } 487 Objects.requireNonNull(field, "field"); 488 Objects.requireNonNull(signStyle, "signStyle"); 489 if (minWidth < 1 || minWidth > 19) { 490 throw new IllegalArgumentException("The minimum width must be from 1 to 19 inclusive but was " + minWidth); 491 } 492 if (maxWidth < 1 || maxWidth > 19) { 493 throw new IllegalArgumentException("The maximum width must be from 1 to 19 inclusive but was " + maxWidth); 494 } 495 if (maxWidth < minWidth) { 496 throw new IllegalArgumentException("The maximum width must exceed or equal the minimum width but " + 497 maxWidth + " < " + minWidth); 498 } 499 NumberPrinterParser pp = new NumberPrinterParser(field, minWidth, maxWidth, signStyle); 500 appendValue(pp); 501 return this; 502 } 503 504 //----------------------------------------------------------------------- 505 /** 506 * Appends the reduced value of a date-time field to the formatter. 507 * <p> 508 * Since fields such as year vary by chronology, it is recommended to use the 509 * {@link #appendValueReduced(TemporalField, int, int, ChronoLocalDate)} date} 510 * variant of this method in most cases. This variant is suitable for 511 * simple fields or working with only the ISO chronology. 512 * <p> 513 * For formatting, the {@code width} and {@code maxWidth} are used to 514 * determine the number of characters to format. 515 * If they are equal then the format is fixed width. 516 * If the value of the field is within the range of the {@code baseValue} using 517 * {@code width} characters then the reduced value is formatted otherwise the value is 518 * truncated to fit {@code maxWidth}. 519 * The rightmost characters are output to match the width, left padding with zero. 520 * <p> 521 * For strict parsing, the number of characters allowed by {@code width} to {@code maxWidth} are parsed. 522 * For lenient parsing, the number of characters must be at least 1 and less than 10. 523 * If the number of digits parsed is equal to {@code width} and the value is positive, 524 * the value of the field is computed to be the first number greater than 525 * or equal to the {@code baseValue} with the same least significant characters, 526 * otherwise the value parsed is the field value. 527 * This allows a reduced value to be entered for values in range of the baseValue 528 * and width and absolute values can be entered for values outside the range. 529 * <p> 530 * For example, a base value of {@code 1980} and a width of {@code 2} will have 531 * valid values from {@code 1980} to {@code 2079}. 532 * During parsing, the text {@code "12"} will result in the value {@code 2012} as that 533 * is the value within the range where the last two characters are "12". 534 * By contrast, parsing the text {@code "1915"} will result in the value {@code 1915}. 535 * 536 * @param field the field to append, not null 537 * @param width the field width of the printed and parsed field, from 1 to 10 538 * @param maxWidth the maximum field width of the printed field, from 1 to 10 539 * @param baseValue the base value of the range of valid values 540 * @return this, for chaining, not null 541 * @throws IllegalArgumentException if the width or base value is invalid 542 */ 543 public DateTimeFormatterBuilder appendValueReduced(TemporalField field, 544 int width, int maxWidth, int baseValue) { 545 Objects.requireNonNull(field, "field"); 546 ReducedPrinterParser pp = new ReducedPrinterParser(field, width, maxWidth, baseValue, null); 547 appendValue(pp); 548 return this; 549 } 550 551 /** 552 * Appends the reduced value of a date-time field to the formatter. 553 * <p> 554 * This is typically used for formatting and parsing a two digit year. 555 * <p> 556 * The base date is used to calculate the full value during parsing. 557 * For example, if the base date is 1950-01-01 then parsed values for 558 * a two digit year parse will be in the range 1950-01-01 to 2049-12-31. 559 * Only the year would be extracted from the date, thus a base date of 560 * 1950-08-25 would also parse to the range 1950-01-01 to 2049-12-31. 561 * This behavior is necessary to support fields such as week-based-year 562 * or other calendar systems where the parsed value does not align with 563 * standard ISO years. 564 * <p> 565 * The exact behavior is as follows. Parse the full set of fields and 566 * determine the effective chronology using the last chronology if 567 * it appears more than once. Then convert the base date to the 568 * effective chronology. Then extract the specified field from the 569 * chronology-specific base date and use it to determine the 570 * {@code baseValue} used below. 571 * <p> 572 * For formatting, the {@code width} and {@code maxWidth} are used to 573 * determine the number of characters to format. 574 * If they are equal then the format is fixed width. 575 * If the value of the field is within the range of the {@code baseValue} using 576 * {@code width} characters then the reduced value is formatted otherwise the value is 577 * truncated to fit {@code maxWidth}. 578 * The rightmost characters are output to match the width, left padding with zero. 579 * <p> 580 * For strict parsing, the number of characters allowed by {@code width} to {@code maxWidth} are parsed. 581 * For lenient parsing, the number of characters must be at least 1 and less than 10. 582 * If the number of digits parsed is equal to {@code width} and the value is positive, 583 * the value of the field is computed to be the first number greater than 584 * or equal to the {@code baseValue} with the same least significant characters, 585 * otherwise the value parsed is the field value. 586 * This allows a reduced value to be entered for values in range of the baseValue 587 * and width and absolute values can be entered for values outside the range. 588 * <p> 589 * For example, a base value of {@code 1980} and a width of {@code 2} will have 590 * valid values from {@code 1980} to {@code 2079}. 591 * During parsing, the text {@code "12"} will result in the value {@code 2012} as that 592 * is the value within the range where the last two characters are "12". 593 * By contrast, parsing the text {@code "1915"} will result in the value {@code 1915}. 594 * 595 * @param field the field to append, not null 596 * @param width the field width of the printed and parsed field, from 1 to 10 597 * @param maxWidth the maximum field width of the printed field, from 1 to 10 598 * @param baseDate the base date used to calculate the base value for the range 599 * of valid values in the parsed chronology, not null 600 * @return this, for chaining, not null 601 * @throws IllegalArgumentException if the width or base value is invalid 602 */ 603 public DateTimeFormatterBuilder appendValueReduced( 604 TemporalField field, int width, int maxWidth, ChronoLocalDate baseDate) { 605 Objects.requireNonNull(field, "field"); 606 Objects.requireNonNull(baseDate, "baseDate"); 607 ReducedPrinterParser pp = new ReducedPrinterParser(field, width, maxWidth, 0, baseDate); 608 appendValue(pp); 609 return this; 610 } 611 612 /** 613 * Appends a fixed or variable width printer-parser handling adjacent value mode. 614 * If a PrinterParser is not active then the new PrinterParser becomes 615 * the active PrinterParser. 616 * Otherwise, the active PrinterParser is modified depending on the new PrinterParser. 617 * If the new PrinterParser is fixed width and has sign style {@code NOT_NEGATIVE} 618 * then its width is added to the active PP and 619 * the new PrinterParser is forced to be fixed width. 620 * If the new PrinterParser is variable width, the active PrinterParser is changed 621 * to be fixed width and the new PrinterParser becomes the active PP. 622 * 623 * @param pp the printer-parser, not null 624 * @return this, for chaining, not null 625 */ 626 private DateTimeFormatterBuilder appendValue(NumberPrinterParser pp) { 627 if (active.valueParserIndex >= 0) { 628 final int activeValueParser = active.valueParserIndex; 629 630 // adjacent parsing mode, update setting in previous parsers 631 NumberPrinterParser basePP = (NumberPrinterParser) active.printerParsers.get(activeValueParser); 632 if (pp.minWidth == pp.maxWidth && pp.signStyle == SignStyle.NOT_NEGATIVE) { 633 // Append the width to the subsequentWidth of the active parser 634 basePP = basePP.withSubsequentWidth(pp.maxWidth); 635 // Append the new parser as a fixed width 636 appendInternal(pp.withFixedWidth()); 637 // Retain the previous active parser 638 active.valueParserIndex = activeValueParser; 639 } else { 640 // Modify the active parser to be fixed width 641 basePP = basePP.withFixedWidth(); 642 // The new parser becomes the mew active parser 643 active.valueParserIndex = appendInternal(pp); 644 } 645 // Replace the modified parser with the updated one 646 active.printerParsers.set(activeValueParser, basePP); 647 } else { 648 // The new Parser becomes the active parser 649 active.valueParserIndex = appendInternal(pp); 650 } 651 return this; 652 } 653 654 //----------------------------------------------------------------------- 655 /** 656 * Appends the fractional value of a date-time field to the formatter. 657 * <p> 658 * The fractional value of the field will be output including the 659 * preceding decimal point. The preceding value is not output. 660 * For example, the second-of-minute value of 15 would be output as {@code .25}. 661 * <p> 662 * The width of the printed fraction can be controlled. Setting the 663 * minimum width to zero will cause no output to be generated. 664 * The printed fraction will have the minimum width necessary between 665 * the minimum and maximum widths - trailing zeroes are omitted. 666 * No rounding occurs due to the maximum width - digits are simply dropped. 667 * <p> 668 * When parsing in strict mode, the number of parsed digits must be between 669 * the minimum and maximum width. When parsing in lenient mode, the minimum 670 * width is considered to be zero and the maximum is nine. 671 * <p> 672 * If the value cannot be obtained then an exception will be thrown. 673 * If the value is negative an exception will be thrown. 674 * If the field does not have a fixed set of valid values then an 675 * exception will be thrown. 676 * If the field value in the date-time to be printed is invalid it 677 * cannot be printed and an exception will be thrown. 678 * 679 * @param field the field to append, not null 680 * @param minWidth the minimum width of the field excluding the decimal point, from 0 to 9 681 * @param maxWidth the maximum width of the field excluding the decimal point, from 1 to 9 682 * @param decimalPoint whether to output the localized decimal point symbol 683 * @return this, for chaining, not null 684 * @throws IllegalArgumentException if the field has a variable set of valid values or 685 * either width is invalid 686 */ 687 public DateTimeFormatterBuilder appendFraction( 688 TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) { 689 appendInternal(new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint)); 690 return this; 691 } 692 693 //----------------------------------------------------------------------- 694 /** 695 * Appends the text of a date-time field to the formatter using the full 696 * text style. 697 * <p> 698 * The text of the field will be output during a format. 699 * The value must be within the valid range of the field. 700 * If the value cannot be obtained then an exception will be thrown. 701 * If the field has no textual representation, then the numeric value will be used. 702 * <p> 703 * The value will be printed as per the normal format of an integer value. 704 * Only negative numbers will be signed. No padding will be added. 705 * 706 * @param field the field to append, not null 707 * @return this, for chaining, not null 708 */ 709 public DateTimeFormatterBuilder appendText(TemporalField field) { 710 return appendText(field, TextStyle.FULL); 711 } 712 713 /** 714 * Appends the text of a date-time field to the formatter. 715 * <p> 716 * The text of the field will be output during a format. 717 * The value must be within the valid range of the field. 718 * If the value cannot be obtained then an exception will be thrown. 719 * If the field has no textual representation, then the numeric value will be used. 720 * <p> 721 * The value will be printed as per the normal format of an integer value. 722 * Only negative numbers will be signed. No padding will be added. 723 * 724 * @param field the field to append, not null 725 * @param textStyle the text style to use, not null 726 * @return this, for chaining, not null 727 */ 728 public DateTimeFormatterBuilder appendText(TemporalField field, TextStyle textStyle) { 729 Objects.requireNonNull(field, "field"); 730 Objects.requireNonNull(textStyle, "textStyle"); 731 appendInternal(new TextPrinterParser(field, textStyle, DateTimeTextProvider.getInstance())); 732 return this; 733 } 734 735 /** 736 * Appends the text of a date-time field to the formatter using the specified 737 * map to supply the text. 738 * <p> 739 * The standard text outputting methods use the localized text in the JDK. 740 * This method allows that text to be specified directly. 741 * The supplied map is not validated by the builder to ensure that formatting or 742 * parsing is possible, thus an invalid map may throw an error during later use. 743 * <p> 744 * Supplying the map of text provides considerable flexibility in formatting and parsing. 745 * For example, a legacy application might require or supply the months of the 746 * year as "JNY", "FBY", "MCH" etc. These do not match the standard set of text 747 * for localized month names. Using this method, a map can be created which 748 * defines the connection between each value and the text: 749 * <pre> 750 * Map<Long, String> map = new HashMap<>(); 751 * map.put(1L, "JNY"); 752 * map.put(2L, "FBY"); 753 * map.put(3L, "MCH"); 754 * ... 755 * builder.appendText(MONTH_OF_YEAR, map); 756 * </pre> 757 * <p> 758 * Other uses might be to output the value with a suffix, such as "1st", "2nd", "3rd", 759 * or as Roman numerals "I", "II", "III", "IV". 760 * <p> 761 * During formatting, the value is obtained and checked that it is in the valid range. 762 * If text is not available for the value then it is output as a number. 763 * During parsing, the parser will match against the map of text and numeric values. 764 * 765 * @param field the field to append, not null 766 * @param textLookup the map from the value to the text 767 * @return this, for chaining, not null 768 */ 769 public DateTimeFormatterBuilder appendText(TemporalField field, Map<Long, String> textLookup) { 770 Objects.requireNonNull(field, "field"); 771 Objects.requireNonNull(textLookup, "textLookup"); 772 Map<Long, String> copy = new LinkedHashMap<>(textLookup); 773 Map<TextStyle, Map<Long, String>> map = Collections.singletonMap(TextStyle.FULL, copy); 774 final LocaleStore store = new LocaleStore(map); 775 DateTimeTextProvider provider = new DateTimeTextProvider() { 776 @Override 777 public String getText(TemporalField field, long value, TextStyle style, Locale locale) { 778 return store.getText(value, style); 779 } 780 @Override 781 public Iterator<Entry<String, Long>> getTextIterator(TemporalField field, TextStyle style, Locale locale) { 782 return store.getTextIterator(style); 783 } 784 }; 785 appendInternal(new TextPrinterParser(field, TextStyle.FULL, provider)); 786 return this; 787 } 788 789 //----------------------------------------------------------------------- 790 /** 791 * Appends an instant using ISO-8601 to the formatter, formatting fractional 792 * digits in groups of three. 793 * <p> 794 * Instants have a fixed output format. 795 * They are converted to a date-time with a zone-offset of UTC and formatted 796 * using the standard ISO-8601 format. 797 * With this method, formatting nano-of-second outputs zero, three, six 798 * or nine digits as necessary. 799 * The localized decimal style is not used. 800 * <p> 801 * The instant is obtained using {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} 802 * and optionally (@code NANO_OF_SECOND). The value of {@code INSTANT_SECONDS} 803 * may be outside the maximum range of {@code LocalDateTime}. 804 * <p> 805 * The {@linkplain ResolverStyle resolver style} has no effect on instant parsing. 806 * The end-of-day time of '24:00' is handled as midnight at the start of the following day. 807 * The leap-second time of '23:59:59' is handled to some degree, see 808 * {@link DateTimeFormatter#parsedLeapSecond()} for full details. 809 * <p> 810 * An alternative to this method is to format/parse the instant as a single 811 * epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}. 812 * 813 * @return this, for chaining, not null 814 */ 815 public DateTimeFormatterBuilder appendInstant() { 816 appendInternal(new InstantPrinterParser(-2)); 817 return this; 818 } 819 820 /** 821 * Appends an instant using ISO-8601 to the formatter with control over 822 * the number of fractional digits. 823 * <p> 824 * Instants have a fixed output format, although this method provides some 825 * control over the fractional digits. They are converted to a date-time 826 * with a zone-offset of UTC and printed using the standard ISO-8601 format. 827 * The localized decimal style is not used. 828 * <p> 829 * The {@code fractionalDigits} parameter allows the output of the fractional 830 * second to be controlled. Specifying zero will cause no fractional digits 831 * to be output. From 1 to 9 will output an increasing number of digits, using 832 * zero right-padding if necessary. The special value -1 is used to output as 833 * many digits as necessary to avoid any trailing zeroes. 834 * <p> 835 * When parsing in strict mode, the number of parsed digits must match the 836 * fractional digits. When parsing in lenient mode, any number of fractional 837 * digits from zero to nine are accepted. 838 * <p> 839 * The instant is obtained using {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} 840 * and optionally (@code NANO_OF_SECOND). The value of {@code INSTANT_SECONDS} 841 * may be outside the maximum range of {@code LocalDateTime}. 842 * <p> 843 * The {@linkplain ResolverStyle resolver style} has no effect on instant parsing. 844 * The end-of-day time of '24:00' is handled as midnight at the start of the following day. 845 * The leap-second time of '23:59:60' is handled to some degree, see 846 * {@link DateTimeFormatter#parsedLeapSecond()} for full details. 847 * <p> 848 * An alternative to this method is to format/parse the instant as a single 849 * epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}. 850 * 851 * @param fractionalDigits the number of fractional second digits to format with, 852 * from 0 to 9, or -1 to use as many digits as necessary 853 * @return this, for chaining, not null 854 * @throws IllegalArgumentException if the number of fractional digits is invalid 855 */ 856 public DateTimeFormatterBuilder appendInstant(int fractionalDigits) { 857 if (fractionalDigits < -1 || fractionalDigits > 9) { 858 throw new IllegalArgumentException("The fractional digits must be from -1 to 9 inclusive but was " + fractionalDigits); 859 } 860 appendInternal(new InstantPrinterParser(fractionalDigits)); 861 return this; 862 } 863 864 //----------------------------------------------------------------------- 865 /** 866 * Appends the zone offset, such as '+01:00', to the formatter. 867 * <p> 868 * This appends an instruction to format/parse the offset ID to the builder. 869 * If in lenient parsing mode, this is equivalent to calling {@code appendOffset("+HH:mm:ss", "Z")}. 870 * Otherwise this is equivalent to calling {@code appendOffset("+HH:MM:ss", "Z")}. 871 * 872 * @return this, for chaining, not null 873 */ 874 public DateTimeFormatterBuilder appendOffsetId() { 875 appendInternal(OffsetIdPrinterParser.INSTANCE_ID_Z); 876 return this; 877 } 878 879 /** 880 * Appends the zone offset, such as '+01:00', to the formatter. 881 * <p> 882 * This appends an instruction to format/parse the offset ID to the builder. 883 * <p> 884 * During formatting, the offset is obtained using a mechanism equivalent 885 * to querying the temporal with {@link TemporalQueries#offset()}. 886 * It will be printed using the format defined below. 887 * If the offset cannot be obtained then an exception is thrown unless the 888 * section of the formatter is optional. 889 * <p> 890 * During parsing, the offset is parsed using the format defined below. 891 * If the offset cannot be parsed then an exception is thrown unless the 892 * section of the formatter is optional. In lenient parsing mode, the minutes 893 * are optional in the patterns +HHMMss and +HH:MM:ss. 894 * <p> 895 * The format of the offset is controlled by a pattern which must be one 896 * of the following: 897 * <ul> 898 * <li>{@code +HH} - hour only, ignoring minute and second 899 * <li>{@code +HHmm} - hour, with minute if non-zero, ignoring second, no colon 900 * <li>{@code +HH:mm} - hour, with minute if non-zero, ignoring second, with colon 901 * <li>{@code +HHMM} - hour and minute, ignoring second, no colon 902 * <li>{@code +HH:MM} - hour and minute, ignoring second, with colon 903 * <li>{@code +HHMMss} - hour and minute, with second if non-zero, no colon 904 * <li>{@code +HH:MM:ss} - hour and minute, with second if non-zero, with colon 905 * <li>{@code +HHMMSS} - hour, minute and second, no colon 906 * <li>{@code +HH:MM:SS} - hour, minute and second, with colon 907 * <li>{@code +HHmmss} - hour, with minute if non-zero or with minute and 908 * second if non-zero, no colon 909 * <li>{@code +HH:mm:ss} - hour, with minute if non-zero or with minute and 910 * second if non-zero, with colon 911 * </ul> 912 * The "no offset" text controls what text is printed when the total amount of 913 * the offset fields to be output is zero. 914 * Example values would be 'Z', '+00:00', 'UTC' or 'GMT'. 915 * Three formats are accepted for parsing UTC - the "no offset" text, and the 916 * plus and minus versions of zero defined by the pattern. 917 * 918 * @param pattern the pattern to use, not null 919 * @param noOffsetText the text to use when the offset is zero, not null 920 * @return this, for chaining, not null 921 * @throws IllegalArgumentException if the pattern is invalid 922 */ 923 public DateTimeFormatterBuilder appendOffset(String pattern, String noOffsetText) { 924 appendInternal(new OffsetIdPrinterParser(pattern, noOffsetText)); 925 return this; 926 } 927 928 /** 929 * Appends the localized zone offset, such as 'GMT+01:00', to the formatter. 930 * <p> 931 * This appends a localized zone offset to the builder, the format of the 932 * localized offset is controlled by the specified {@link FormatStyle style} 933 * to this method: 934 * <ul> 935 * <li>{@link TextStyle#FULL full} - formats with localized offset text, such 936 * as 'GMT, 2-digit hour and minute field, optional second field if non-zero, 937 * and colon. 938 * <li>{@link TextStyle#SHORT short} - formats with localized offset text, 939 * such as 'GMT, hour without leading zero, optional 2-digit minute and 940 * second if non-zero, and colon. 941 * </ul> 942 * <p> 943 * During formatting, the offset is obtained using a mechanism equivalent 944 * to querying the temporal with {@link TemporalQueries#offset()}. 945 * If the offset cannot be obtained then an exception is thrown unless the 946 * section of the formatter is optional. 947 * <p> 948 * During parsing, the offset is parsed using the format defined above. 949 * If the offset cannot be parsed then an exception is thrown unless the 950 * section of the formatter is optional. 951 * 952 * @param style the format style to use, not null 953 * @return this, for chaining, not null 954 * @throws IllegalArgumentException if style is neither {@link TextStyle#FULL 955 * full} nor {@link TextStyle#SHORT short} 956 */ 957 public DateTimeFormatterBuilder appendLocalizedOffset(TextStyle style) { 958 Objects.requireNonNull(style, "style"); 959 if (style != TextStyle.FULL && style != TextStyle.SHORT) { 960 throw new IllegalArgumentException("Style must be either full or short"); 961 } 962 appendInternal(new LocalizedOffsetIdPrinterParser(style)); 963 return this; 964 } 965 966 //----------------------------------------------------------------------- 967 /** 968 * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to the formatter. 969 * <p> 970 * This appends an instruction to format/parse the zone ID to the builder. 971 * The zone ID is obtained in a strict manner suitable for {@code ZonedDateTime}. 972 * By contrast, {@code OffsetDateTime} does not have a zone ID suitable 973 * for use with this method, see {@link #appendZoneOrOffsetId()}. 974 * <p> 975 * During formatting, the zone is obtained using a mechanism equivalent 976 * to querying the temporal with {@link TemporalQueries#zoneId()}. 977 * It will be printed using the result of {@link ZoneId#getId()}. 978 * If the zone cannot be obtained then an exception is thrown unless the 979 * section of the formatter is optional. 980 * <p> 981 * During parsing, the text must match a known zone or offset. 982 * There are two types of zone ID, offset-based, such as '+01:30' and 983 * region-based, such as 'Europe/London'. These are parsed differently. 984 * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser 985 * expects an offset-based zone and will not match region-based zones. 986 * The offset ID, such as '+02:30', may be at the start of the parse, 987 * or prefixed by 'UT', 'UTC' or 'GMT'. The offset ID parsing is 988 * equivalent to using {@link #appendOffset(String, String)} using the 989 * arguments 'HH:MM:ss' and the no offset string '0'. 990 * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot 991 * match a following offset ID, then {@link ZoneOffset#UTC} is selected. 992 * In all other cases, the list of known region-based zones is used to 993 * find the longest available match. If no match is found, and the parse 994 * starts with 'Z', then {@code ZoneOffset.UTC} is selected. 995 * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting. 996 * <p> 997 * For example, the following will parse: 998 * <pre> 999 * "Europe/London" -- ZoneId.of("Europe/London") 1000 * "Z" -- ZoneOffset.UTC 1001 * "UT" -- ZoneId.of("UT") 1002 * "UTC" -- ZoneId.of("UTC") 1003 * "GMT" -- ZoneId.of("GMT") 1004 * "+01:30" -- ZoneOffset.of("+01:30") 1005 * "UT+01:30" -- ZoneOffset.of("+01:30") 1006 * "UTC+01:30" -- ZoneOffset.of("+01:30") 1007 * "GMT+01:30" -- ZoneOffset.of("+01:30") 1008 * </pre> 1009 * 1010 * @return this, for chaining, not null 1011 * @see #appendZoneRegionId() 1012 */ 1013 public DateTimeFormatterBuilder appendZoneId() { 1014 appendInternal(new ZoneIdPrinterParser(TemporalQueries.zoneId(), "ZoneId()")); 1015 return this; 1016 } 1017 1018 /** 1019 * Appends the time-zone region ID, such as 'Europe/Paris', to the formatter, 1020 * rejecting the zone ID if it is a {@code ZoneOffset}. 1021 * <p> 1022 * This appends an instruction to format/parse the zone ID to the builder 1023 * only if it is a region-based ID. 1024 * <p> 1025 * During formatting, the zone is obtained using a mechanism equivalent 1026 * to querying the temporal with {@link TemporalQueries#zoneId()}. 1027 * If the zone is a {@code ZoneOffset} or it cannot be obtained then 1028 * an exception is thrown unless the section of the formatter is optional. 1029 * If the zone is not an offset, then the zone will be printed using 1030 * the zone ID from {@link ZoneId#getId()}. 1031 * <p> 1032 * During parsing, the text must match a known zone or offset. 1033 * There are two types of zone ID, offset-based, such as '+01:30' and 1034 * region-based, such as 'Europe/London'. These are parsed differently. 1035 * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser 1036 * expects an offset-based zone and will not match region-based zones. 1037 * The offset ID, such as '+02:30', may be at the start of the parse, 1038 * or prefixed by 'UT', 'UTC' or 'GMT'. The offset ID parsing is 1039 * equivalent to using {@link #appendOffset(String, String)} using the 1040 * arguments 'HH:MM:ss' and the no offset string '0'. 1041 * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot 1042 * match a following offset ID, then {@link ZoneOffset#UTC} is selected. 1043 * In all other cases, the list of known region-based zones is used to 1044 * find the longest available match. If no match is found, and the parse 1045 * starts with 'Z', then {@code ZoneOffset.UTC} is selected. 1046 * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting. 1047 * <p> 1048 * For example, the following will parse: 1049 * <pre> 1050 * "Europe/London" -- ZoneId.of("Europe/London") 1051 * "Z" -- ZoneOffset.UTC 1052 * "UT" -- ZoneId.of("UT") 1053 * "UTC" -- ZoneId.of("UTC") 1054 * "GMT" -- ZoneId.of("GMT") 1055 * "+01:30" -- ZoneOffset.of("+01:30") 1056 * "UT+01:30" -- ZoneOffset.of("+01:30") 1057 * "UTC+01:30" -- ZoneOffset.of("+01:30") 1058 * "GMT+01:30" -- ZoneOffset.of("+01:30") 1059 * </pre> 1060 * <p> 1061 * Note that this method is identical to {@code appendZoneId()} except 1062 * in the mechanism used to obtain the zone. 1063 * Note also that parsing accepts offsets, whereas formatting will never 1064 * produce one. 1065 * 1066 * @return this, for chaining, not null 1067 * @see #appendZoneId() 1068 */ 1069 public DateTimeFormatterBuilder appendZoneRegionId() { 1070 appendInternal(new ZoneIdPrinterParser(QUERY_REGION_ONLY, "ZoneRegionId()")); 1071 return this; 1072 } 1073 1074 /** 1075 * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to 1076 * the formatter, using the best available zone ID. 1077 * <p> 1078 * This appends an instruction to format/parse the best available 1079 * zone or offset ID to the builder. 1080 * The zone ID is obtained in a lenient manner that first attempts to 1081 * find a true zone ID, such as that on {@code ZonedDateTime}, and 1082 * then attempts to find an offset, such as that on {@code OffsetDateTime}. 1083 * <p> 1084 * During formatting, the zone is obtained using a mechanism equivalent 1085 * to querying the temporal with {@link TemporalQueries#zone()}. 1086 * It will be printed using the result of {@link ZoneId#getId()}. 1087 * If the zone cannot be obtained then an exception is thrown unless the 1088 * section of the formatter is optional. 1089 * <p> 1090 * During parsing, the text must match a known zone or offset. 1091 * There are two types of zone ID, offset-based, such as '+01:30' and 1092 * region-based, such as 'Europe/London'. These are parsed differently. 1093 * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser 1094 * expects an offset-based zone and will not match region-based zones. 1095 * The offset ID, such as '+02:30', may be at the start of the parse, 1096 * or prefixed by 'UT', 'UTC' or 'GMT'. The offset ID parsing is 1097 * equivalent to using {@link #appendOffset(String, String)} using the 1098 * arguments 'HH:MM:ss' and the no offset string '0'. 1099 * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot 1100 * match a following offset ID, then {@link ZoneOffset#UTC} is selected. 1101 * In all other cases, the list of known region-based zones is used to 1102 * find the longest available match. If no match is found, and the parse 1103 * starts with 'Z', then {@code ZoneOffset.UTC} is selected. 1104 * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting. 1105 * <p> 1106 * For example, the following will parse: 1107 * <pre> 1108 * "Europe/London" -- ZoneId.of("Europe/London") 1109 * "Z" -- ZoneOffset.UTC 1110 * "UT" -- ZoneId.of("UT") 1111 * "UTC" -- ZoneId.of("UTC") 1112 * "GMT" -- ZoneId.of("GMT") 1113 * "+01:30" -- ZoneOffset.of("+01:30") 1114 * "UT+01:30" -- ZoneOffset.of("UT+01:30") 1115 * "UTC+01:30" -- ZoneOffset.of("UTC+01:30") 1116 * "GMT+01:30" -- ZoneOffset.of("GMT+01:30") 1117 * </pre> 1118 * <p> 1119 * Note that this method is identical to {@code appendZoneId()} except 1120 * in the mechanism used to obtain the zone. 1121 * 1122 * @return this, for chaining, not null 1123 * @see #appendZoneId() 1124 */ 1125 public DateTimeFormatterBuilder appendZoneOrOffsetId() { 1126 appendInternal(new ZoneIdPrinterParser(TemporalQueries.zone(), "ZoneOrOffsetId()")); 1127 return this; 1128 } 1129 1130 /** 1131 * Appends the time-zone name, such as 'British Summer Time', to the formatter. 1132 * <p> 1133 * This appends an instruction to format/parse the textual name of the zone to 1134 * the builder. 1135 * <p> 1136 * During formatting, the zone is obtained using a mechanism equivalent 1137 * to querying the temporal with {@link TemporalQueries#zoneId()}. 1138 * If the zone is a {@code ZoneOffset} it will be printed using the 1139 * result of {@link ZoneOffset#getId()}. 1140 * If the zone is not an offset, the textual name will be looked up 1141 * for the locale set in the {@link DateTimeFormatter}. 1142 * If the temporal object being printed represents an instant, then the text 1143 * will be the summer or winter time text as appropriate. 1144 * If the lookup for text does not find any suitable result, then the 1145 * {@link ZoneId#getId() ID} will be printed instead. 1146 * If the zone cannot be obtained then an exception is thrown unless the 1147 * section of the formatter is optional. 1148 * <p> 1149 * During parsing, either the textual zone name, the zone ID or the offset 1150 * is accepted. Many textual zone names are not unique, such as CST can be 1151 * for both "Central Standard Time" and "China Standard Time". In this 1152 * situation, the zone id will be determined by the region information from 1153 * formatter's {@link DateTimeFormatter#getLocale() locale} and the standard 1154 * zone id for that area, for example, America/New_York for the America Eastern 1155 * zone. The {@link #appendZoneText(TextStyle, Set)} may be used 1156 * to specify a set of preferred {@link ZoneId} in this situation. 1157 * 1158 * @param textStyle the text style to use, not null 1159 * @return this, for chaining, not null 1160 */ 1161 public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle) { 1162 appendInternal(new ZoneTextPrinterParser(textStyle, null)); 1163 return this; 1164 } 1165 1166 /** 1167 * Appends the time-zone name, such as 'British Summer Time', to the formatter. 1168 * <p> 1169 * This appends an instruction to format/parse the textual name of the zone to 1170 * the builder. 1171 * <p> 1172 * During formatting, the zone is obtained using a mechanism equivalent 1173 * to querying the temporal with {@link TemporalQueries#zoneId()}. 1174 * If the zone is a {@code ZoneOffset} it will be printed using the 1175 * result of {@link ZoneOffset#getId()}. 1176 * If the zone is not an offset, the textual name will be looked up 1177 * for the locale set in the {@link DateTimeFormatter}. 1178 * If the temporal object being printed represents an instant, then the text 1179 * will be the summer or winter time text as appropriate. 1180 * If the lookup for text does not find any suitable result, then the 1181 * {@link ZoneId#getId() ID} will be printed instead. 1182 * If the zone cannot be obtained then an exception is thrown unless the 1183 * section of the formatter is optional. 1184 * <p> 1185 * During parsing, either the textual zone name, the zone ID or the offset 1186 * is accepted. Many textual zone names are not unique, such as CST can be 1187 * for both "Central Standard Time" and "China Standard Time". In this 1188 * situation, the zone id will be determined by the region information from 1189 * formatter's {@link DateTimeFormatter#getLocale() locale} and the standard 1190 * zone id for that area, for example, America/New_York for the America Eastern 1191 * zone. This method also allows a set of preferred {@link ZoneId} to be 1192 * specified for parsing. The matched preferred zone id will be used if the 1193 * textural zone name being parsed is not unique. 1194 * <p> 1195 * If the zone cannot be parsed then an exception is thrown unless the 1196 * section of the formatter is optional. 1197 * 1198 * @param textStyle the text style to use, not null 1199 * @param preferredZones the set of preferred zone ids, not null 1200 * @return this, for chaining, not null 1201 */ 1202 public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle, 1203 Set<ZoneId> preferredZones) { 1204 Objects.requireNonNull(preferredZones, "preferredZones"); 1205 appendInternal(new ZoneTextPrinterParser(textStyle, preferredZones)); 1206 return this; 1207 } 1208 1209 //----------------------------------------------------------------------- 1210 /** 1211 * Appends the chronology ID, such as 'ISO' or 'ThaiBuddhist', to the formatter. 1212 * <p> 1213 * This appends an instruction to format/parse the chronology ID to the builder. 1214 * <p> 1215 * During formatting, the chronology is obtained using a mechanism equivalent 1216 * to querying the temporal with {@link TemporalQueries#chronology()}. 1217 * It will be printed using the result of {@link Chronology#getId()}. 1218 * If the chronology cannot be obtained then an exception is thrown unless the 1219 * section of the formatter is optional. 1220 * <p> 1221 * During parsing, the chronology is parsed and must match one of the chronologies 1222 * in {@link Chronology#getAvailableChronologies()}. 1223 * If the chronology cannot be parsed then an exception is thrown unless the 1224 * section of the formatter is optional. 1225 * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting. 1226 * 1227 * @return this, for chaining, not null 1228 */ 1229 public DateTimeFormatterBuilder appendChronologyId() { 1230 appendInternal(new ChronoPrinterParser(null)); 1231 return this; 1232 } 1233 1234 /** 1235 * Appends the chronology name to the formatter. 1236 * <p> 1237 * The calendar system name will be output during a format. 1238 * If the chronology cannot be obtained then an exception will be thrown. 1239 * 1240 * @param textStyle the text style to use, not null 1241 * @return this, for chaining, not null 1242 */ 1243 public DateTimeFormatterBuilder appendChronologyText(TextStyle textStyle) { 1244 Objects.requireNonNull(textStyle, "textStyle"); 1245 appendInternal(new ChronoPrinterParser(textStyle)); 1246 return this; 1247 } 1248 1249 //----------------------------------------------------------------------- 1250 /** 1251 * Appends a localized date-time pattern to the formatter. 1252 * <p> 1253 * This appends a localized section to the builder, suitable for outputting 1254 * a date, time or date-time combination. The format of the localized 1255 * section is lazily looked up based on four items: 1256 * <ul> 1257 * <li>the {@code dateStyle} specified to this method 1258 * <li>the {@code timeStyle} specified to this method 1259 * <li>the {@code Locale} of the {@code DateTimeFormatter} 1260 * <li>the {@code Chronology}, selecting the best available 1261 * </ul> 1262 * During formatting, the chronology is obtained from the temporal object 1263 * being formatted, which may have been overridden by 1264 * {@link DateTimeFormatter#withChronology(Chronology)}. 1265 * <p> 1266 * During parsing, if a chronology has already been parsed, then it is used. 1267 * Otherwise the default from {@code DateTimeFormatter.withChronology(Chronology)} 1268 * is used, with {@code IsoChronology} as the fallback. 1269 * <p> 1270 * Note that this method provides similar functionality to methods on 1271 * {@code DateFormat} such as {@link java.text.DateFormat#getDateTimeInstance(int, int)}. 1272 * 1273 * @param dateStyle the date style to use, null means no date required 1274 * @param timeStyle the time style to use, null means no time required 1275 * @return this, for chaining, not null 1276 * @throws IllegalArgumentException if both the date and time styles are null 1277 */ 1278 public DateTimeFormatterBuilder appendLocalized(FormatStyle dateStyle, FormatStyle timeStyle) { 1279 if (dateStyle == null && timeStyle == null) { 1280 throw new IllegalArgumentException("Either the date or time style must be non-null"); 1281 } 1282 appendInternal(new LocalizedPrinterParser(dateStyle, timeStyle)); 1283 return this; 1284 } 1285 1286 //----------------------------------------------------------------------- 1287 /** 1288 * Appends a character literal to the formatter. 1289 * <p> 1290 * This character will be output during a format. 1291 * 1292 * @param literal the literal to append, not null 1293 * @return this, for chaining, not null 1294 */ 1295 public DateTimeFormatterBuilder appendLiteral(char literal) { 1296 appendInternal(new CharLiteralPrinterParser(literal)); 1297 return this; 1298 } 1299 1300 /** 1301 * Appends a string literal to the formatter. 1302 * <p> 1303 * This string will be output during a format. 1304 * <p> 1305 * If the literal is empty, nothing is added to the formatter. 1306 * 1307 * @param literal the literal to append, not null 1308 * @return this, for chaining, not null 1309 */ 1310 public DateTimeFormatterBuilder appendLiteral(String literal) { 1311 Objects.requireNonNull(literal, "literal"); 1312 if (literal.length() > 0) { 1313 if (literal.length() == 1) { 1314 appendInternal(new CharLiteralPrinterParser(literal.charAt(0))); 1315 } else { 1316 appendInternal(new StringLiteralPrinterParser(literal)); 1317 } 1318 } 1319 return this; 1320 } 1321 1322 //----------------------------------------------------------------------- 1323 /** 1324 * Appends all the elements of a formatter to the builder. 1325 * <p> 1326 * This method has the same effect as appending each of the constituent 1327 * parts of the formatter directly to this builder. 1328 * 1329 * @param formatter the formatter to add, not null 1330 * @return this, for chaining, not null 1331 */ 1332 public DateTimeFormatterBuilder append(DateTimeFormatter formatter) { 1333 Objects.requireNonNull(formatter, "formatter"); 1334 appendInternal(formatter.toPrinterParser(false)); 1335 return this; 1336 } 1337 1338 /** 1339 * Appends a formatter to the builder which will optionally format/parse. 1340 * <p> 1341 * This method has the same effect as appending each of the constituent 1342 * parts directly to this builder surrounded by an {@link #optionalStart()} and 1343 * {@link #optionalEnd()}. 1344 * <p> 1345 * The formatter will format if data is available for all the fields contained within it. 1346 * The formatter will parse if the string matches, otherwise no error is returned. 1347 * 1348 * @param formatter the formatter to add, not null 1349 * @return this, for chaining, not null 1350 */ 1351 public DateTimeFormatterBuilder appendOptional(DateTimeFormatter formatter) { 1352 Objects.requireNonNull(formatter, "formatter"); 1353 appendInternal(formatter.toPrinterParser(true)); 1354 return this; 1355 } 1356 1357 //----------------------------------------------------------------------- 1358 /** 1359 * Appends the elements defined by the specified pattern to the builder. 1360 * <p> 1361 * All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. 1362 * The characters '#', '{' and '}' are reserved for future use. 1363 * The characters '[' and ']' indicate optional patterns. 1364 * The following pattern letters are defined: 1365 * <pre> 1366 * Symbol Meaning Presentation Examples 1367 * ------ ------- ------------ ------- 1368 * G era text AD; Anno Domini; A 1369 * u year year 2004; 04 1370 * y year-of-era year 2004; 04 1371 * D day-of-year number 189 1372 * M/L month-of-year number/text 7; 07; Jul; July; J 1373 * d day-of-month number 10 1374 * 1375 * Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter 1376 * Y week-based-year year 1996; 96 1377 * w week-of-week-based-year number 27 1378 * W week-of-month number 4 1379 * E day-of-week text Tue; Tuesday; T 1380 * e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T 1381 * F week-of-month number 3 1382 * 1383 * a am-pm-of-day text PM 1384 * h clock-hour-of-am-pm (1-12) number 12 1385 * K hour-of-am-pm (0-11) number 0 1386 * k clock-hour-of-am-pm (1-24) number 0 1387 * 1388 * H hour-of-day (0-23) number 0 1389 * m minute-of-hour number 30 1390 * s second-of-minute number 55 1391 * S fraction-of-second fraction 978 1392 * A milli-of-day number 1234 1393 * n nano-of-second number 987654321 1394 * N nano-of-day number 1234000000 1395 * 1396 * V time-zone ID zone-id America/Los_Angeles; Z; -08:30 1397 * z time-zone name zone-name Pacific Standard Time; PST 1398 * O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00; 1399 * X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15; 1400 * x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15; 1401 * Z zone-offset offset-Z +0000; -0800; -08:00; 1402 * 1403 * p pad next pad modifier 1 1404 * 1405 * ' escape for text delimiter 1406 * '' single quote literal ' 1407 * [ optional section start 1408 * ] optional section end 1409 * # reserved for future use 1410 * { reserved for future use 1411 * } reserved for future use 1412 * </pre> 1413 * <p> 1414 * The count of pattern letters determine the format. 1415 * See <a href="DateTimeFormatter.html#patterns">DateTimeFormatter</a> for a user-focused description of the patterns. 1416 * The following tables define how the pattern letters map to the builder. 1417 * <p> 1418 * <b>Date fields</b>: Pattern letters to output a date. 1419 * <pre> 1420 * Pattern Count Equivalent builder methods 1421 * ------- ----- -------------------------- 1422 * G 1 appendText(ChronoField.ERA, TextStyle.SHORT) 1423 * GG 2 appendText(ChronoField.ERA, TextStyle.SHORT) 1424 * GGG 3 appendText(ChronoField.ERA, TextStyle.SHORT) 1425 * GGGG 4 appendText(ChronoField.ERA, TextStyle.FULL) 1426 * GGGGG 5 appendText(ChronoField.ERA, TextStyle.NARROW) 1427 * 1428 * u 1 appendValue(ChronoField.YEAR, 1, 19, SignStyle.NORMAL); 1429 * uu 2 appendValueReduced(ChronoField.YEAR, 2, 2000); 1430 * uuu 3 appendValue(ChronoField.YEAR, 3, 19, SignStyle.NORMAL); 1431 * u..u 4..n appendValue(ChronoField.YEAR, n, 19, SignStyle.EXCEEDS_PAD); 1432 * y 1 appendValue(ChronoField.YEAR_OF_ERA, 1, 19, SignStyle.NORMAL); 1433 * yy 2 appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2000); 1434 * yyy 3 appendValue(ChronoField.YEAR_OF_ERA, 3, 19, SignStyle.NORMAL); 1435 * y..y 4..n appendValue(ChronoField.YEAR_OF_ERA, n, 19, SignStyle.EXCEEDS_PAD); 1436 * Y 1 append special localized WeekFields element for numeric week-based-year 1437 * YY 2 append special localized WeekFields element for reduced numeric week-based-year 2 digits; 1438 * YYY 3 append special localized WeekFields element for numeric week-based-year (3, 19, SignStyle.NORMAL); 1439 * Y..Y 4..n append special localized WeekFields element for numeric week-based-year (n, 19, SignStyle.EXCEEDS_PAD); 1440 * 1441 * Q 1 appendValue(IsoFields.QUARTER_OF_YEAR); 1442 * QQ 2 appendValue(IsoFields.QUARTER_OF_YEAR, 2); 1443 * QQQ 3 appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.SHORT) 1444 * QQQQ 4 appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.FULL) 1445 * QQQQQ 5 appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.NARROW) 1446 * q 1 appendValue(IsoFields.QUARTER_OF_YEAR); 1447 * qq 2 appendValue(IsoFields.QUARTER_OF_YEAR, 2); 1448 * qqq 3 appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.SHORT_STANDALONE) 1449 * qqqq 4 appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.FULL_STANDALONE) 1450 * qqqqq 5 appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.NARROW_STANDALONE) 1451 * 1452 * M 1 appendValue(ChronoField.MONTH_OF_YEAR); 1453 * MM 2 appendValue(ChronoField.MONTH_OF_YEAR, 2); 1454 * MMM 3 appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT) 1455 * MMMM 4 appendText(ChronoField.MONTH_OF_YEAR, TextStyle.FULL) 1456 * MMMMM 5 appendText(ChronoField.MONTH_OF_YEAR, TextStyle.NARROW) 1457 * L 1 appendValue(ChronoField.MONTH_OF_YEAR); 1458 * LL 2 appendValue(ChronoField.MONTH_OF_YEAR, 2); 1459 * LLL 3 appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT_STANDALONE) 1460 * LLLL 4 appendText(ChronoField.MONTH_OF_YEAR, TextStyle.FULL_STANDALONE) 1461 * LLLLL 5 appendText(ChronoField.MONTH_OF_YEAR, TextStyle.NARROW_STANDALONE) 1462 * 1463 * w 1 append special localized WeekFields element for numeric week-of-year 1464 * ww 2 append special localized WeekFields element for numeric week-of-year, zero-padded 1465 * W 1 append special localized WeekFields element for numeric week-of-month 1466 * d 1 appendValue(ChronoField.DAY_OF_MONTH) 1467 * dd 2 appendValue(ChronoField.DAY_OF_MONTH, 2) 1468 * D 1 appendValue(ChronoField.DAY_OF_YEAR) 1469 * DD 2 appendValue(ChronoField.DAY_OF_YEAR, 2) 1470 * DDD 3 appendValue(ChronoField.DAY_OF_YEAR, 3) 1471 * F 1 appendValue(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH) 1472 * E 1 appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT) 1473 * EE 2 appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT) 1474 * EEE 3 appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT) 1475 * EEEE 4 appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL) 1476 * EEEEE 5 appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW) 1477 * e 1 append special localized WeekFields element for numeric day-of-week 1478 * ee 2 append special localized WeekFields element for numeric day-of-week, zero-padded 1479 * eee 3 appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT) 1480 * eeee 4 appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL) 1481 * eeeee 5 appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW) 1482 * c 1 append special localized WeekFields element for numeric day-of-week 1483 * ccc 3 appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT_STANDALONE) 1484 * cccc 4 appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL_STANDALONE) 1485 * ccccc 5 appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW_STANDALONE) 1486 * </pre> 1487 * <p> 1488 * <b>Time fields</b>: Pattern letters to output a time. 1489 * <pre> 1490 * Pattern Count Equivalent builder methods 1491 * ------- ----- -------------------------- 1492 * a 1 appendText(ChronoField.AMPM_OF_DAY, TextStyle.SHORT) 1493 * h 1 appendValue(ChronoField.CLOCK_HOUR_OF_AMPM) 1494 * hh 2 appendValue(ChronoField.CLOCK_HOUR_OF_AMPM, 2) 1495 * H 1 appendValue(ChronoField.HOUR_OF_DAY) 1496 * HH 2 appendValue(ChronoField.HOUR_OF_DAY, 2) 1497 * k 1 appendValue(ChronoField.CLOCK_HOUR_OF_DAY) 1498 * kk 2 appendValue(ChronoField.CLOCK_HOUR_OF_DAY, 2) 1499 * K 1 appendValue(ChronoField.HOUR_OF_AMPM) 1500 * KK 2 appendValue(ChronoField.HOUR_OF_AMPM, 2) 1501 * m 1 appendValue(ChronoField.MINUTE_OF_HOUR) 1502 * mm 2 appendValue(ChronoField.MINUTE_OF_HOUR, 2) 1503 * s 1 appendValue(ChronoField.SECOND_OF_MINUTE) 1504 * ss 2 appendValue(ChronoField.SECOND_OF_MINUTE, 2) 1505 * 1506 * S..S 1..n appendFraction(ChronoField.NANO_OF_SECOND, n, n, false) 1507 * A 1 appendValue(ChronoField.MILLI_OF_DAY) 1508 * A..A 2..n appendValue(ChronoField.MILLI_OF_DAY, n) 1509 * n 1 appendValue(ChronoField.NANO_OF_SECOND) 1510 * n..n 2..n appendValue(ChronoField.NANO_OF_SECOND, n) 1511 * N 1 appendValue(ChronoField.NANO_OF_DAY) 1512 * N..N 2..n appendValue(ChronoField.NANO_OF_DAY, n) 1513 * </pre> 1514 * <p> 1515 * <b>Zone ID</b>: Pattern letters to output {@code ZoneId}. 1516 * <pre> 1517 * Pattern Count Equivalent builder methods 1518 * ------- ----- -------------------------- 1519 * VV 2 appendZoneId() 1520 * z 1 appendZoneText(TextStyle.SHORT) 1521 * zz 2 appendZoneText(TextStyle.SHORT) 1522 * zzz 3 appendZoneText(TextStyle.SHORT) 1523 * zzzz 4 appendZoneText(TextStyle.FULL) 1524 * </pre> 1525 * <p> 1526 * <b>Zone offset</b>: Pattern letters to output {@code ZoneOffset}. 1527 * <pre> 1528 * Pattern Count Equivalent builder methods 1529 * ------- ----- -------------------------- 1530 * O 1 appendLocalizedOffsetPrefixed(TextStyle.SHORT); 1531 * OOOO 4 appendLocalizedOffsetPrefixed(TextStyle.FULL); 1532 * X 1 appendOffset("+HHmm","Z") 1533 * XX 2 appendOffset("+HHMM","Z") 1534 * XXX 3 appendOffset("+HH:MM","Z") 1535 * XXXX 4 appendOffset("+HHMMss","Z") 1536 * XXXXX 5 appendOffset("+HH:MM:ss","Z") 1537 * x 1 appendOffset("+HHmm","+00") 1538 * xx 2 appendOffset("+HHMM","+0000") 1539 * xxx 3 appendOffset("+HH:MM","+00:00") 1540 * xxxx 4 appendOffset("+HHMMss","+0000") 1541 * xxxxx 5 appendOffset("+HH:MM:ss","+00:00") 1542 * Z 1 appendOffset("+HHMM","+0000") 1543 * ZZ 2 appendOffset("+HHMM","+0000") 1544 * ZZZ 3 appendOffset("+HHMM","+0000") 1545 * ZZZZ 4 appendLocalizedOffset(TextStyle.FULL); 1546 * ZZZZZ 5 appendOffset("+HH:MM:ss","Z") 1547 * </pre> 1548 * <p> 1549 * <b>Modifiers</b>: Pattern letters that modify the rest of the pattern: 1550 * <pre> 1551 * Pattern Count Equivalent builder methods 1552 * ------- ----- -------------------------- 1553 * [ 1 optionalStart() 1554 * ] 1 optionalEnd() 1555 * p..p 1..n padNext(n) 1556 * </pre> 1557 * <p> 1558 * Any sequence of letters not specified above, unrecognized letter or 1559 * reserved character will throw an exception. 1560 * Future versions may add to the set of patterns. 1561 * It is recommended to use single quotes around all characters that you want 1562 * to output directly to ensure that future changes do not break your application. 1563 * <p> 1564 * Note that the pattern string is similar, but not identical, to 1565 * {@link java.text.SimpleDateFormat SimpleDateFormat}. 1566 * The pattern string is also similar, but not identical, to that defined by the 1567 * Unicode Common Locale Data Repository (CLDR/LDML). 1568 * Pattern letters 'X' and 'u' are aligned with Unicode CLDR/LDML. 1569 * By contrast, {@code SimpleDateFormat} uses 'u' for the numeric day of week. 1570 * Pattern letters 'y' and 'Y' parse years of two digits and more than 4 digits differently. 1571 * Pattern letters 'n', 'A', 'N', and 'p' are added. 1572 * Number types will reject large numbers. 1573 * 1574 * @param pattern the pattern to add, not null 1575 * @return this, for chaining, not null 1576 * @throws IllegalArgumentException if the pattern is invalid 1577 */ 1578 public DateTimeFormatterBuilder appendPattern(String pattern) { 1579 Objects.requireNonNull(pattern, "pattern"); 1580 parsePattern(pattern); 1581 return this; 1582 } 1583 1584 private void parsePattern(String pattern) { 1585 for (int pos = 0; pos < pattern.length(); pos++) { 1586 char cur = pattern.charAt(pos); 1587 if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) { 1588 int start = pos++; 1589 for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++); // short loop 1590 int count = pos - start; 1591 // padding 1592 if (cur == 'p') { 1593 int pad = 0; 1594 if (pos < pattern.length()) { 1595 cur = pattern.charAt(pos); 1596 if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) { 1597 pad = count; 1598 start = pos++; 1599 for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++); // short loop 1600 count = pos - start; 1601 } 1602 } 1603 if (pad == 0) { 1604 throw new IllegalArgumentException( 1605 "Pad letter 'p' must be followed by valid pad pattern: " + pattern); 1606 } 1607 padNext(pad); // pad and continue parsing 1608 } 1609 // main rules 1610 TemporalField field = FIELD_MAP.get(cur); 1611 if (field != null) { 1612 parseField(cur, count, field); 1613 } else if (cur == 'z') { 1614 if (count > 4) { 1615 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1616 } else if (count == 4) { 1617 appendZoneText(TextStyle.FULL); 1618 } else { 1619 appendZoneText(TextStyle.SHORT); 1620 } 1621 } else if (cur == 'V') { 1622 if (count != 2) { 1623 throw new IllegalArgumentException("Pattern letter count must be 2: " + cur); 1624 } 1625 appendZoneId(); 1626 } else if (cur == 'Z') { 1627 if (count < 4) { 1628 appendOffset("+HHMM", "+0000"); 1629 } else if (count == 4) { 1630 appendLocalizedOffset(TextStyle.FULL); 1631 } else if (count == 5) { 1632 appendOffset("+HH:MM:ss","Z"); 1633 } else { 1634 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1635 } 1636 } else if (cur == 'O') { 1637 if (count == 1) { 1638 appendLocalizedOffset(TextStyle.SHORT); 1639 } else if (count == 4) { 1640 appendLocalizedOffset(TextStyle.FULL); 1641 } else { 1642 throw new IllegalArgumentException("Pattern letter count must be 1 or 4: " + cur); 1643 } 1644 } else if (cur == 'X') { 1645 if (count > 5) { 1646 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1647 } 1648 appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count == 1 ? 0 : 1)], "Z"); 1649 } else if (cur == 'x') { 1650 if (count > 5) { 1651 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1652 } 1653 String zero = (count == 1 ? "+00" : (count % 2 == 0 ? "+0000" : "+00:00")); 1654 appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count == 1 ? 0 : 1)], zero); 1655 } else if (cur == 'W') { 1656 // Fields defined by Locale 1657 if (count > 1) { 1658 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1659 } 1660 appendInternal(new WeekBasedFieldPrinterParser(cur, count)); 1661 } else if (cur == 'w') { 1662 // Fields defined by Locale 1663 if (count > 2) { 1664 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1665 } 1666 appendInternal(new WeekBasedFieldPrinterParser(cur, count)); 1667 } else if (cur == 'Y') { 1668 // Fields defined by Locale 1669 appendInternal(new WeekBasedFieldPrinterParser(cur, count)); 1670 } else { 1671 throw new IllegalArgumentException("Unknown pattern letter: " + cur); 1672 } 1673 pos--; 1674 1675 } else if (cur == '\'') { 1676 // parse literals 1677 int start = pos++; 1678 for ( ; pos < pattern.length(); pos++) { 1679 if (pattern.charAt(pos) == '\'') { 1680 if (pos + 1 < pattern.length() && pattern.charAt(pos + 1) == '\'') { 1681 pos++; 1682 } else { 1683 break; // end of literal 1684 } 1685 } 1686 } 1687 if (pos >= pattern.length()) { 1688 throw new IllegalArgumentException("Pattern ends with an incomplete string literal: " + pattern); 1689 } 1690 String str = pattern.substring(start + 1, pos); 1691 if (str.length() == 0) { 1692 appendLiteral('\''); 1693 } else { 1694 appendLiteral(str.replace("''", "'")); 1695 } 1696 1697 } else if (cur == '[') { 1698 optionalStart(); 1699 1700 } else if (cur == ']') { 1701 if (active.parent == null) { 1702 throw new IllegalArgumentException("Pattern invalid as it contains ] without previous ["); 1703 } 1704 optionalEnd(); 1705 1706 } else if (cur == '{' || cur == '}' || cur == '#') { 1707 throw new IllegalArgumentException("Pattern includes reserved character: '" + cur + "'"); 1708 } else { 1709 appendLiteral(cur); 1710 } 1711 } 1712 } 1713 1714 @SuppressWarnings("fallthrough") 1715 private void parseField(char cur, int count, TemporalField field) { 1716 boolean standalone = false; 1717 switch (cur) { 1718 case 'u': 1719 case 'y': 1720 if (count == 2) { 1721 appendValueReduced(field, 2, 2, ReducedPrinterParser.BASE_DATE); 1722 } else if (count < 4) { 1723 appendValue(field, count, 19, SignStyle.NORMAL); 1724 } else { 1725 appendValue(field, count, 19, SignStyle.EXCEEDS_PAD); 1726 } 1727 break; 1728 case 'c': 1729 if (count == 2) { 1730 throw new IllegalArgumentException("Invalid pattern \"cc\""); 1731 } 1732 /*fallthrough*/ 1733 case 'L': 1734 case 'q': 1735 standalone = true; 1736 /*fallthrough*/ 1737 case 'M': 1738 case 'Q': 1739 case 'E': 1740 case 'e': 1741 switch (count) { 1742 case 1: 1743 case 2: 1744 if (cur == 'c' || cur == 'e') { 1745 appendInternal(new WeekBasedFieldPrinterParser(cur, count)); 1746 } else if (cur == 'E') { 1747 appendText(field, TextStyle.SHORT); 1748 } else { 1749 if (count == 1) { 1750 appendValue(field); 1751 } else { 1752 appendValue(field, 2); 1753 } 1754 } 1755 break; 1756 case 3: 1757 appendText(field, standalone ? TextStyle.SHORT_STANDALONE : TextStyle.SHORT); 1758 break; 1759 case 4: 1760 appendText(field, standalone ? TextStyle.FULL_STANDALONE : TextStyle.FULL); 1761 break; 1762 case 5: 1763 appendText(field, standalone ? TextStyle.NARROW_STANDALONE : TextStyle.NARROW); 1764 break; 1765 default: 1766 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1767 } 1768 break; 1769 case 'a': 1770 if (count == 1) { 1771 appendText(field, TextStyle.SHORT); 1772 } else { 1773 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1774 } 1775 break; 1776 case 'G': 1777 switch (count) { 1778 case 1: 1779 case 2: 1780 case 3: 1781 appendText(field, TextStyle.SHORT); 1782 break; 1783 case 4: 1784 appendText(field, TextStyle.FULL); 1785 break; 1786 case 5: 1787 appendText(field, TextStyle.NARROW); 1788 break; 1789 default: 1790 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1791 } 1792 break; 1793 case 'S': 1794 appendFraction(NANO_OF_SECOND, count, count, false); 1795 break; 1796 case 'F': 1797 if (count == 1) { 1798 appendValue(field); 1799 } else { 1800 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1801 } 1802 break; 1803 case 'd': 1804 case 'h': 1805 case 'H': 1806 case 'k': 1807 case 'K': 1808 case 'm': 1809 case 's': 1810 if (count == 1) { 1811 appendValue(field); 1812 } else if (count == 2) { 1813 appendValue(field, count); 1814 } else { 1815 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1816 } 1817 break; 1818 case 'D': 1819 if (count == 1) { 1820 appendValue(field); 1821 } else if (count <= 3) { 1822 appendValue(field, count); 1823 } else { 1824 throw new IllegalArgumentException("Too many pattern letters: " + cur); 1825 } 1826 break; 1827 default: 1828 if (count == 1) { 1829 appendValue(field); 1830 } else { 1831 appendValue(field, count); 1832 } 1833 break; 1834 } 1835 } 1836 1837 /** Map of letters to fields. */ 1838 private static final Map<Character, TemporalField> FIELD_MAP = new HashMap<>(); 1839 static { 1840 // SDF = SimpleDateFormat 1841 FIELD_MAP.put('G', ChronoField.ERA); // SDF, LDML (different to both for 1/2 chars) 1842 FIELD_MAP.put('y', ChronoField.YEAR_OF_ERA); // SDF, LDML 1843 FIELD_MAP.put('u', ChronoField.YEAR); // LDML (different in SDF) 1844 FIELD_MAP.put('Q', IsoFields.QUARTER_OF_YEAR); // LDML (removed quarter from 310) 1845 FIELD_MAP.put('q', IsoFields.QUARTER_OF_YEAR); // LDML (stand-alone) 1846 FIELD_MAP.put('M', ChronoField.MONTH_OF_YEAR); // SDF, LDML 1847 FIELD_MAP.put('L', ChronoField.MONTH_OF_YEAR); // SDF, LDML (stand-alone) 1848 FIELD_MAP.put('D', ChronoField.DAY_OF_YEAR); // SDF, LDML 1849 FIELD_MAP.put('d', ChronoField.DAY_OF_MONTH); // SDF, LDML 1850 FIELD_MAP.put('F', ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH); // SDF, LDML 1851 FIELD_MAP.put('E', ChronoField.DAY_OF_WEEK); // SDF, LDML (different to both for 1/2 chars) 1852 FIELD_MAP.put('c', ChronoField.DAY_OF_WEEK); // LDML (stand-alone) 1853 FIELD_MAP.put('e', ChronoField.DAY_OF_WEEK); // LDML (needs localized week number) 1854 FIELD_MAP.put('a', ChronoField.AMPM_OF_DAY); // SDF, LDML 1855 FIELD_MAP.put('H', ChronoField.HOUR_OF_DAY); // SDF, LDML 1856 FIELD_MAP.put('k', ChronoField.CLOCK_HOUR_OF_DAY); // SDF, LDML 1857 FIELD_MAP.put('K', ChronoField.HOUR_OF_AMPM); // SDF, LDML 1858 FIELD_MAP.put('h', ChronoField.CLOCK_HOUR_OF_AMPM); // SDF, LDML 1859 FIELD_MAP.put('m', ChronoField.MINUTE_OF_HOUR); // SDF, LDML 1860 FIELD_MAP.put('s', ChronoField.SECOND_OF_MINUTE); // SDF, LDML 1861 FIELD_MAP.put('S', ChronoField.NANO_OF_SECOND); // LDML (SDF uses milli-of-second number) 1862 FIELD_MAP.put('A', ChronoField.MILLI_OF_DAY); // LDML 1863 FIELD_MAP.put('n', ChronoField.NANO_OF_SECOND); // 310 (proposed for LDML) 1864 FIELD_MAP.put('N', ChronoField.NANO_OF_DAY); // 310 (proposed for LDML) 1865 // 310 - z - time-zone names, matches LDML and SimpleDateFormat 1 to 4 1866 // 310 - Z - matches SimpleDateFormat and LDML 1867 // 310 - V - time-zone id, matches LDML 1868 // 310 - p - prefix for padding 1869 // 310 - X - matches LDML, almost matches SDF for 1, exact match 2&3, extended 4&5 1870 // 310 - x - matches LDML 1871 // 310 - w, W, and Y are localized forms matching LDML 1872 // LDML - U - cycle year name, not supported by 310 yet 1873 // LDML - l - deprecated 1874 // LDML - j - not relevant 1875 // LDML - g - modified-julian-day 1876 // LDML - v,V - extended time-zone names 1877 } 1878 1879 //----------------------------------------------------------------------- 1880 /** 1881 * Causes the next added printer/parser to pad to a fixed width using a space. 1882 * <p> 1883 * This padding will pad to a fixed width using spaces. 1884 * <p> 1885 * During formatting, the decorated element will be output and then padded 1886 * to the specified width. An exception will be thrown during formatting if 1887 * the pad width is exceeded. 1888 * <p> 1889 * During parsing, the padding and decorated element are parsed. 1890 * If parsing is lenient, then the pad width is treated as a maximum. 1891 * The padding is parsed greedily. Thus, if the decorated element starts with 1892 * the pad character, it will not be parsed. 1893 * 1894 * @param padWidth the pad width, 1 or greater 1895 * @return this, for chaining, not null 1896 * @throws IllegalArgumentException if pad width is too small 1897 */ 1898 public DateTimeFormatterBuilder padNext(int padWidth) { 1899 return padNext(padWidth, ' '); 1900 } 1901 1902 /** 1903 * Causes the next added printer/parser to pad to a fixed width. 1904 * <p> 1905 * This padding is intended for padding other than zero-padding. 1906 * Zero-padding should be achieved using the appendValue methods. 1907 * <p> 1908 * During formatting, the decorated element will be output and then padded 1909 * to the specified width. An exception will be thrown during formatting if 1910 * the pad width is exceeded. 1911 * <p> 1912 * During parsing, the padding and decorated element are parsed. 1913 * If parsing is lenient, then the pad width is treated as a maximum. 1914 * If parsing is case insensitive, then the pad character is matched ignoring case. 1915 * The padding is parsed greedily. Thus, if the decorated element starts with 1916 * the pad character, it will not be parsed. 1917 * 1918 * @param padWidth the pad width, 1 or greater 1919 * @param padChar the pad character 1920 * @return this, for chaining, not null 1921 * @throws IllegalArgumentException if pad width is too small 1922 */ 1923 public DateTimeFormatterBuilder padNext(int padWidth, char padChar) { 1924 if (padWidth < 1) { 1925 throw new IllegalArgumentException("The pad width must be at least one but was " + padWidth); 1926 } 1927 active.padNextWidth = padWidth; 1928 active.padNextChar = padChar; 1929 active.valueParserIndex = -1; 1930 return this; 1931 } 1932 1933 //----------------------------------------------------------------------- 1934 /** 1935 * Mark the start of an optional section. 1936 * <p> 1937 * The output of formatting can include optional sections, which may be nested. 1938 * An optional section is started by calling this method and ended by calling 1939 * {@link #optionalEnd()} or by ending the build process. 1940 * <p> 1941 * All elements in the optional section are treated as optional. 1942 * During formatting, the section is only output if data is available in the 1943 * {@code TemporalAccessor} for all the elements in the section. 1944 * During parsing, the whole section may be missing from the parsed string. 1945 * <p> 1946 * For example, consider a builder setup as 1947 * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2)}. 1948 * The optional section ends automatically at the end of the builder. 1949 * During formatting, the minute will only be output if its value can be obtained from the date-time. 1950 * During parsing, the input will be successfully parsed whether the minute is present or not. 1951 * 1952 * @return this, for chaining, not null 1953 */ 1954 public DateTimeFormatterBuilder optionalStart() { 1955 active.valueParserIndex = -1; 1956 active = new DateTimeFormatterBuilder(active, true); 1957 return this; 1958 } 1959 1960 /** 1961 * Ends an optional section. 1962 * <p> 1963 * The output of formatting can include optional sections, which may be nested. 1964 * An optional section is started by calling {@link #optionalStart()} and ended 1965 * using this method (or at the end of the builder). 1966 * <p> 1967 * Calling this method without having previously called {@code optionalStart} 1968 * will throw an exception. 1969 * Calling this method immediately after calling {@code optionalStart} has no effect 1970 * on the formatter other than ending the (empty) optional section. 1971 * <p> 1972 * All elements in the optional section are treated as optional. 1973 * During formatting, the section is only output if data is available in the 1974 * {@code TemporalAccessor} for all the elements in the section. 1975 * During parsing, the whole section may be missing from the parsed string. 1976 * <p> 1977 * For example, consider a builder setup as 1978 * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2).optionalEnd()}. 1979 * During formatting, the minute will only be output if its value can be obtained from the date-time. 1980 * During parsing, the input will be successfully parsed whether the minute is present or not. 1981 * 1982 * @return this, for chaining, not null 1983 * @throws IllegalStateException if there was no previous call to {@code optionalStart} 1984 */ 1985 public DateTimeFormatterBuilder optionalEnd() { 1986 if (active.parent == null) { 1987 throw new IllegalStateException("Cannot call optionalEnd() as there was no previous call to optionalStart()"); 1988 } 1989 if (active.printerParsers.size() > 0) { 1990 CompositePrinterParser cpp = new CompositePrinterParser(active.printerParsers, active.optional); 1991 active = active.parent; 1992 appendInternal(cpp); 1993 } else { 1994 active = active.parent; 1995 } 1996 return this; 1997 } 1998 1999 //----------------------------------------------------------------------- 2000 /** 2001 * Appends a printer and/or parser to the internal list handling padding. 2002 * 2003 * @param pp the printer-parser to add, not null 2004 * @return the index into the active parsers list 2005 */ 2006 private int appendInternal(DateTimePrinterParser pp) { 2007 Objects.requireNonNull(pp, "pp"); 2008 if (active.padNextWidth > 0) { 2009 if (pp != null) { 2010 pp = new PadPrinterParserDecorator(pp, active.padNextWidth, active.padNextChar); 2011 } 2012 active.padNextWidth = 0; 2013 active.padNextChar = 0; 2014 } 2015 active.printerParsers.add(pp); 2016 active.valueParserIndex = -1; 2017 return active.printerParsers.size() - 1; 2018 } 2019 2020 //----------------------------------------------------------------------- 2021 /** 2022 * Completes this builder by creating the {@code DateTimeFormatter} 2023 * using the default locale. 2024 * <p> 2025 * This will create a formatter with the {@linkplain Locale#getDefault(Locale.Category) default FORMAT locale}. 2026 * Numbers will be printed and parsed using the standard DecimalStyle. 2027 * The resolver style will be {@link ResolverStyle#SMART SMART}. 2028 * <p> 2029 * Calling this method will end any open optional sections by repeatedly 2030 * calling {@link #optionalEnd()} before creating the formatter. 2031 * <p> 2032 * This builder can still be used after creating the formatter if desired, 2033 * although the state may have been changed by calls to {@code optionalEnd}. 2034 * 2035 * @return the created formatter, not null 2036 */ 2037 public DateTimeFormatter toFormatter() { 2038 return toFormatter(Locale.getDefault(Locale.Category.FORMAT)); 2039 } 2040 2041 /** 2042 * Completes this builder by creating the {@code DateTimeFormatter} 2043 * using the specified locale. 2044 * <p> 2045 * This will create a formatter with the specified locale. 2046 * Numbers will be printed and parsed using the standard DecimalStyle. 2047 * The resolver style will be {@link ResolverStyle#SMART SMART}. 2048 * <p> 2049 * Calling this method will end any open optional sections by repeatedly 2050 * calling {@link #optionalEnd()} before creating the formatter. 2051 * <p> 2052 * This builder can still be used after creating the formatter if desired, 2053 * although the state may have been changed by calls to {@code optionalEnd}. 2054 * 2055 * @param locale the locale to use for formatting, not null 2056 * @return the created formatter, not null 2057 */ 2058 public DateTimeFormatter toFormatter(Locale locale) { 2059 return toFormatter(locale, ResolverStyle.SMART, null); 2060 } 2061 2062 /** 2063 * Completes this builder by creating the formatter. 2064 * This uses the default locale. 2065 * 2066 * @param resolverStyle the resolver style to use, not null 2067 * @return the created formatter, not null 2068 */ 2069 DateTimeFormatter toFormatter(ResolverStyle resolverStyle, Chronology chrono) { 2070 return toFormatter(Locale.getDefault(Locale.Category.FORMAT), resolverStyle, chrono); 2071 } 2072 2073 /** 2074 * Completes this builder by creating the formatter. 2075 * 2076 * @param locale the locale to use for formatting, not null 2077 * @param chrono the chronology to use, may be null 2078 * @return the created formatter, not null 2079 */ 2080 private DateTimeFormatter toFormatter(Locale locale, ResolverStyle resolverStyle, Chronology chrono) { 2081 Objects.requireNonNull(locale, "locale"); 2082 while (active.parent != null) { 2083 optionalEnd(); 2084 } 2085 CompositePrinterParser pp = new CompositePrinterParser(printerParsers, false); 2086 return new DateTimeFormatter(pp, locale, DecimalStyle.STANDARD, 2087 resolverStyle, null, chrono, null); 2088 } 2089 2090 //----------------------------------------------------------------------- 2091 /** 2092 * Strategy for formatting/parsing date-time information. 2093 * <p> 2094 * The printer may format any part, or the whole, of the input date-time object. 2095 * Typically, a complete format is constructed from a number of smaller 2096 * units, each outputting a single field. 2097 * <p> 2098 * The parser may parse any piece of text from the input, storing the result 2099 * in the context. Typically, each individual parser will just parse one 2100 * field, such as the day-of-month, storing the value in the context. 2101 * Once the parse is complete, the caller will then resolve the parsed values 2102 * to create the desired object, such as a {@code LocalDate}. 2103 * <p> 2104 * The parse position will be updated during the parse. Parsing will start at 2105 * the specified index and the return value specifies the new parse position 2106 * for the next parser. If an error occurs, the returned index will be negative 2107 * and will have the error position encoded using the complement operator. 2108 * 2109 * @implSpec 2110 * This interface must be implemented with care to ensure other classes operate correctly. 2111 * All implementations that can be instantiated must be final, immutable and thread-safe. 2112 * <p> 2113 * The context is not a thread-safe object and a new instance will be created 2114 * for each format that occurs. The context must not be stored in an instance 2115 * variable or shared with any other threads. 2116 */ 2117 interface DateTimePrinterParser { 2118 2119 /** 2120 * Prints the date-time object to the buffer. 2121 * <p> 2122 * The context holds information to use during the format. 2123 * It also contains the date-time information to be printed. 2124 * <p> 2125 * The buffer must not be mutated beyond the content controlled by the implementation. 2126 * 2127 * @param context the context to format using, not null 2128 * @param buf the buffer to append to, not null 2129 * @return false if unable to query the value from the date-time, true otherwise 2130 * @throws DateTimeException if the date-time cannot be printed successfully 2131 */ 2132 boolean format(DateTimePrintContext context, StringBuilder buf); 2133 2134 /** 2135 * Parses text into date-time information. 2136 * <p> 2137 * The context holds information to use during the parse. 2138 * It is also used to store the parsed date-time information. 2139 * 2140 * @param context the context to use and parse into, not null 2141 * @param text the input text to parse, not null 2142 * @param position the position to start parsing at, from 0 to the text length 2143 * @return the new parse position, where negative means an error with the 2144 * error position encoded using the complement ~ operator 2145 * @throws NullPointerException if the context or text is null 2146 * @throws IndexOutOfBoundsException if the position is invalid 2147 */ 2148 int parse(DateTimeParseContext context, CharSequence text, int position); 2149 } 2150 2151 //----------------------------------------------------------------------- 2152 /** 2153 * Composite printer and parser. 2154 */ 2155 static final class CompositePrinterParser implements DateTimePrinterParser { 2156 private final DateTimePrinterParser[] printerParsers; 2157 private final boolean optional; 2158 2159 CompositePrinterParser(List<DateTimePrinterParser> printerParsers, boolean optional) { 2160 this(printerParsers.toArray(new DateTimePrinterParser[printerParsers.size()]), optional); 2161 } 2162 2163 CompositePrinterParser(DateTimePrinterParser[] printerParsers, boolean optional) { 2164 this.printerParsers = printerParsers; 2165 this.optional = optional; 2166 } 2167 2168 /** 2169 * Returns a copy of this printer-parser with the optional flag changed. 2170 * 2171 * @param optional the optional flag to set in the copy 2172 * @return the new printer-parser, not null 2173 */ 2174 public CompositePrinterParser withOptional(boolean optional) { 2175 if (optional == this.optional) { 2176 return this; 2177 } 2178 return new CompositePrinterParser(printerParsers, optional); 2179 } 2180 2181 @Override 2182 public boolean format(DateTimePrintContext context, StringBuilder buf) { 2183 int length = buf.length(); 2184 if (optional) { 2185 context.startOptional(); 2186 } 2187 try { 2188 for (DateTimePrinterParser pp : printerParsers) { 2189 if (pp.format(context, buf) == false) { 2190 buf.setLength(length); // reset buffer 2191 return true; 2192 } 2193 } 2194 } finally { 2195 if (optional) { 2196 context.endOptional(); 2197 } 2198 } 2199 return true; 2200 } 2201 2202 @Override 2203 public int parse(DateTimeParseContext context, CharSequence text, int position) { 2204 if (optional) { 2205 context.startOptional(); 2206 int pos = position; 2207 for (DateTimePrinterParser pp : printerParsers) { 2208 pos = pp.parse(context, text, pos); 2209 if (pos < 0) { 2210 context.endOptional(false); 2211 return position; // return original position 2212 } 2213 } 2214 context.endOptional(true); 2215 return pos; 2216 } else { 2217 for (DateTimePrinterParser pp : printerParsers) { 2218 position = pp.parse(context, text, position); 2219 if (position < 0) { 2220 break; 2221 } 2222 } 2223 return position; 2224 } 2225 } 2226 2227 @Override 2228 public String toString() { 2229 StringBuilder buf = new StringBuilder(); 2230 if (printerParsers != null) { 2231 buf.append(optional ? "[" : "("); 2232 for (DateTimePrinterParser pp : printerParsers) { 2233 buf.append(pp); 2234 } 2235 buf.append(optional ? "]" : ")"); 2236 } 2237 return buf.toString(); 2238 } 2239 } 2240 2241 //----------------------------------------------------------------------- 2242 /** 2243 * Pads the output to a fixed width. 2244 */ 2245 static final class PadPrinterParserDecorator implements DateTimePrinterParser { 2246 private final DateTimePrinterParser printerParser; 2247 private final int padWidth; 2248 private final char padChar; 2249 2250 /** 2251 * Constructor. 2252 * 2253 * @param printerParser the printer, not null 2254 * @param padWidth the width to pad to, 1 or greater 2255 * @param padChar the pad character 2256 */ 2257 PadPrinterParserDecorator(DateTimePrinterParser printerParser, int padWidth, char padChar) { 2258 // input checked by DateTimeFormatterBuilder 2259 this.printerParser = printerParser; 2260 this.padWidth = padWidth; 2261 this.padChar = padChar; 2262 } 2263 2264 @Override 2265 public boolean format(DateTimePrintContext context, StringBuilder buf) { 2266 int preLen = buf.length(); 2267 if (printerParser.format(context, buf) == false) { 2268 return false; 2269 } 2270 int len = buf.length() - preLen; 2271 if (len > padWidth) { 2272 throw new DateTimeException( 2273 "Cannot print as output of " + len + " characters exceeds pad width of " + padWidth); 2274 } 2275 for (int i = 0; i < padWidth - len; i++) { 2276 buf.insert(preLen, padChar); 2277 } 2278 return true; 2279 } 2280 2281 @Override 2282 public int parse(DateTimeParseContext context, CharSequence text, int position) { 2283 // cache context before changed by decorated parser 2284 final boolean strict = context.isStrict(); 2285 // parse 2286 if (position > text.length()) { 2287 throw new IndexOutOfBoundsException(); 2288 } 2289 if (position == text.length()) { 2290 return ~position; // no more characters in the string 2291 } 2292 int endPos = position + padWidth; 2293 if (endPos > text.length()) { 2294 if (strict) { 2295 return ~position; // not enough characters in the string to meet the parse width 2296 } 2297 endPos = text.length(); 2298 } 2299 int pos = position; 2300 while (pos < endPos && context.charEquals(text.charAt(pos), padChar)) { 2301 pos++; 2302 } 2303 text = text.subSequence(0, endPos); 2304 int resultPos = printerParser.parse(context, text, pos); 2305 if (resultPos != endPos && strict) { 2306 return ~(position + pos); // parse of decorated field didn't parse to the end 2307 } 2308 return resultPos; 2309 } 2310 2311 @Override 2312 public String toString() { 2313 return "Pad(" + printerParser + "," + padWidth + (padChar == ' ' ? ")" : ",'" + padChar + "')"); 2314 } 2315 } 2316 2317 //----------------------------------------------------------------------- 2318 /** 2319 * Enumeration to apply simple parse settings. 2320 */ 2321 static enum SettingsParser implements DateTimePrinterParser { 2322 SENSITIVE, 2323 INSENSITIVE, 2324 STRICT, 2325 LENIENT; 2326 2327 @Override 2328 public boolean format(DateTimePrintContext context, StringBuilder buf) { 2329 return true; // nothing to do here 2330 } 2331 2332 @Override 2333 public int parse(DateTimeParseContext context, CharSequence text, int position) { 2334 // using ordinals to avoid javac synthetic inner class 2335 switch (ordinal()) { 2336 case 0: context.setCaseSensitive(true); break; 2337 case 1: context.setCaseSensitive(false); break; 2338 case 2: context.setStrict(true); break; 2339 case 3: context.setStrict(false); break; 2340 } 2341 return position; 2342 } 2343 2344 @Override 2345 public String toString() { 2346 // using ordinals to avoid javac synthetic inner class 2347 switch (ordinal()) { 2348 case 0: return "ParseCaseSensitive(true)"; 2349 case 1: return "ParseCaseSensitive(false)"; 2350 case 2: return "ParseStrict(true)"; 2351 case 3: return "ParseStrict(false)"; 2352 } 2353 throw new IllegalStateException("Unreachable"); 2354 } 2355 } 2356 2357 //----------------------------------------------------------------------- 2358 /** 2359 * Defaults a value into the parse if not currently present. 2360 */ 2361 static class DefaultValueParser implements DateTimePrinterParser { 2362 private final TemporalField field; 2363 private final long value; 2364 2365 DefaultValueParser(TemporalField field, long value) { 2366 this.field = field; 2367 this.value = value; 2368 } 2369 2370 public boolean format(DateTimePrintContext context, StringBuilder buf) { 2371 return true; 2372 } 2373 2374 public int parse(DateTimeParseContext context, CharSequence text, int position) { 2375 if (context.getParsed(field) == null) { 2376 context.setParsedField(field, value, position, position); 2377 } 2378 return position; 2379 } 2380 } 2381 2382 //----------------------------------------------------------------------- 2383 /** 2384 * Prints or parses a character literal. 2385 */ 2386 static final class CharLiteralPrinterParser implements DateTimePrinterParser { 2387 private final char literal; 2388 2389 CharLiteralPrinterParser(char literal) { 2390 this.literal = literal; 2391 } 2392 2393 @Override 2394 public boolean format(DateTimePrintContext context, StringBuilder buf) { 2395 buf.append(literal); 2396 return true; 2397 } 2398 2399 @Override 2400 public int parse(DateTimeParseContext context, CharSequence text, int position) { 2401 int length = text.length(); 2402 if (position == length) { 2403 return ~position; 2404 } 2405 char ch = text.charAt(position); 2406 if (ch != literal) { 2407 if (context.isCaseSensitive() || 2408 (Character.toUpperCase(ch) != Character.toUpperCase(literal) && 2409 Character.toLowerCase(ch) != Character.toLowerCase(literal))) { 2410 return ~position; 2411 } 2412 } 2413 return position + 1; 2414 } 2415 2416 @Override 2417 public String toString() { 2418 if (literal == '\'') { 2419 return "''"; 2420 } 2421 return "'" + literal + "'"; 2422 } 2423 } 2424 2425 //----------------------------------------------------------------------- 2426 /** 2427 * Prints or parses a string literal. 2428 */ 2429 static final class StringLiteralPrinterParser implements DateTimePrinterParser { 2430 private final String literal; 2431 2432 StringLiteralPrinterParser(String literal) { 2433 this.literal = literal; // validated by caller 2434 } 2435 2436 @Override 2437 public boolean format(DateTimePrintContext context, StringBuilder buf) { 2438 buf.append(literal); 2439 return true; 2440 } 2441 2442 @Override 2443 public int parse(DateTimeParseContext context, CharSequence text, int position) { 2444 int length = text.length(); 2445 if (position > length || position < 0) { 2446 throw new IndexOutOfBoundsException(); 2447 } 2448 if (context.subSequenceEquals(text, position, literal, 0, literal.length()) == false) { 2449 return ~position; 2450 } 2451 return position + literal.length(); 2452 } 2453 2454 @Override 2455 public String toString() { 2456 String converted = literal.replace("'", "''"); 2457 return "'" + converted + "'"; 2458 } 2459 } 2460 2461 //----------------------------------------------------------------------- 2462 /** 2463 * Prints and parses a numeric date-time field with optional padding. 2464 */ 2465 static class NumberPrinterParser implements DateTimePrinterParser { 2466 2467 /** 2468 * Array of 10 to the power of n. 2469 */ 2470 static final long[] EXCEED_POINTS = new long[] { 2471 0L, 2472 10L, 2473 100L, 2474 1000L, 2475 10000L, 2476 100000L, 2477 1000000L, 2478 10000000L, 2479 100000000L, 2480 1000000000L, 2481 10000000000L, 2482 }; 2483 2484 final TemporalField field; 2485 final int minWidth; 2486 final int maxWidth; 2487 private final SignStyle signStyle; 2488 final int subsequentWidth; 2489 2490 /** 2491 * Constructor. 2492 * 2493 * @param field the field to format, not null 2494 * @param minWidth the minimum field width, from 1 to 19 2495 * @param maxWidth the maximum field width, from minWidth to 19 2496 * @param signStyle the positive/negative sign style, not null 2497 */ 2498 NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) { 2499 // validated by caller 2500 this.field = field; 2501 this.minWidth = minWidth; 2502 this.maxWidth = maxWidth; 2503 this.signStyle = signStyle; 2504 this.subsequentWidth = 0; 2505 } 2506 2507 /** 2508 * Constructor. 2509 * 2510 * @param field the field to format, not null 2511 * @param minWidth the minimum field width, from 1 to 19 2512 * @param maxWidth the maximum field width, from minWidth to 19 2513 * @param signStyle the positive/negative sign style, not null 2514 * @param subsequentWidth the width of subsequent non-negative numbers, 0 or greater, 2515 * -1 if fixed width due to active adjacent parsing 2516 */ 2517 protected NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle, int subsequentWidth) { 2518 // validated by caller 2519 this.field = field; 2520 this.minWidth = minWidth; 2521 this.maxWidth = maxWidth; 2522 this.signStyle = signStyle; 2523 this.subsequentWidth = subsequentWidth; 2524 } 2525 2526 /** 2527 * Returns a new instance with fixed width flag set. 2528 * 2529 * @return a new updated printer-parser, not null 2530 */ 2531 NumberPrinterParser withFixedWidth() { 2532 if (subsequentWidth == -1) { 2533 return this; 2534 } 2535 return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, -1); 2536 } 2537 2538 /** 2539 * Returns a new instance with an updated subsequent width. 2540 * 2541 * @param subsequentWidth the width of subsequent non-negative numbers, 0 or greater 2542 * @return a new updated printer-parser, not null 2543 */ 2544 NumberPrinterParser withSubsequentWidth(int subsequentWidth) { 2545 return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, this.subsequentWidth + subsequentWidth); 2546 } 2547 2548 @Override 2549 public boolean format(DateTimePrintContext context, StringBuilder buf) { 2550 Long valueLong = context.getValue(field); 2551 if (valueLong == null) { 2552 return false; 2553 } 2554 long value = getValue(context, valueLong); 2555 DecimalStyle decimalStyle = context.getDecimalStyle(); 2556 String str = (value == Long.MIN_VALUE ? "9223372036854775808" : Long.toString(Math.abs(value))); 2557 if (str.length() > maxWidth) { 2558 throw new DateTimeException("Field " + field + 2559 " cannot be printed as the value " + value + 2560 " exceeds the maximum print width of " + maxWidth); 2561 } 2562 str = decimalStyle.convertNumberToI18N(str); 2563 2564 if (value >= 0) { 2565 switch (signStyle) { 2566 case EXCEEDS_PAD: 2567 if (minWidth < 19 && value >= EXCEED_POINTS[minWidth]) { 2568 buf.append(decimalStyle.getPositiveSign()); 2569 } 2570 break; 2571 case ALWAYS: 2572 buf.append(decimalStyle.getPositiveSign()); 2573 break; 2574 } 2575 } else { 2576 switch (signStyle) { 2577 case NORMAL: 2578 case EXCEEDS_PAD: 2579 case ALWAYS: 2580 buf.append(decimalStyle.getNegativeSign()); 2581 break; 2582 case NOT_NEGATIVE: 2583 throw new DateTimeException("Field " + field + 2584 " cannot be printed as the value " + value + 2585 " cannot be negative according to the SignStyle"); 2586 } 2587 } 2588 for (int i = 0; i < minWidth - str.length(); i++) { 2589 buf.append(decimalStyle.getZeroDigit()); 2590 } 2591 buf.append(str); 2592 return true; 2593 } 2594 2595 /** 2596 * Gets the value to output. 2597 * 2598 * @param context the context 2599 * @param value the value of the field, not null 2600 * @return the value 2601 */ 2602 long getValue(DateTimePrintContext context, long value) { 2603 return value; 2604 } 2605 2606 /** 2607 * For NumberPrinterParser, the width is fixed depending on the 2608 * minWidth, maxWidth, signStyle and whether subsequent fields are fixed. 2609 * @param context the context 2610 * @return true if the field is fixed width 2611 * @see DateTimeFormatterBuilder#appendValue(java.time.temporal.TemporalField, int) 2612 */ 2613 boolean isFixedWidth(DateTimeParseContext context) { 2614 return subsequentWidth == -1 || 2615 (subsequentWidth > 0 && minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE); 2616 } 2617 2618 @Override 2619 public int parse(DateTimeParseContext context, CharSequence text, int position) { 2620 int length = text.length(); 2621 if (position == length) { 2622 return ~position; 2623 } 2624 char sign = text.charAt(position); // IOOBE if invalid position 2625 boolean negative = false; 2626 boolean positive = false; 2627 if (sign == context.getDecimalStyle().getPositiveSign()) { 2628 if (signStyle.parse(true, context.isStrict(), minWidth == maxWidth) == false) { 2629 return ~position; 2630 } 2631 positive = true; 2632 position++; 2633 } else if (sign == context.getDecimalStyle().getNegativeSign()) { 2634 if (signStyle.parse(false, context.isStrict(), minWidth == maxWidth) == false) { 2635 return ~position; 2636 } 2637 negative = true; 2638 position++; 2639 } else { 2640 if (signStyle == SignStyle.ALWAYS && context.isStrict()) { 2641 return ~position; 2642 } 2643 } 2644 int effMinWidth = (context.isStrict() || isFixedWidth(context) ? minWidth : 1); 2645 int minEndPos = position + effMinWidth; 2646 if (minEndPos > length) { 2647 return ~position; 2648 } 2649 int effMaxWidth = (context.isStrict() || isFixedWidth(context) ? maxWidth : 9) + Math.max(subsequentWidth, 0); 2650 long total = 0; 2651 BigInteger totalBig = null; 2652 int pos = position; 2653 for (int pass = 0; pass < 2; pass++) { 2654 int maxEndPos = Math.min(pos + effMaxWidth, length); 2655 while (pos < maxEndPos) { 2656 char ch = text.charAt(pos++); 2657 int digit = context.getDecimalStyle().convertToDigit(ch); 2658 if (digit < 0) { 2659 pos--; 2660 if (pos < minEndPos) { 2661 return ~position; // need at least min width digits 2662 } 2663 break; 2664 } 2665 if ((pos - position) > 18) { 2666 if (totalBig == null) { 2667 totalBig = BigInteger.valueOf(total); 2668 } 2669 totalBig = totalBig.multiply(BigInteger.TEN).add(BigInteger.valueOf(digit)); 2670 } else { 2671 total = total * 10 + digit; 2672 } 2673 } 2674 if (subsequentWidth > 0 && pass == 0) { 2675 // re-parse now we know the correct width 2676 int parseLen = pos - position; 2677 effMaxWidth = Math.max(effMinWidth, parseLen - subsequentWidth); 2678 pos = position; 2679 total = 0; 2680 totalBig = null; 2681 } else { 2682 break; 2683 } 2684 } 2685 if (negative) { 2686 if (totalBig != null) { 2687 if (totalBig.equals(BigInteger.ZERO) && context.isStrict()) { 2688 return ~(position - 1); // minus zero not allowed 2689 } 2690 totalBig = totalBig.negate(); 2691 } else { 2692 if (total == 0 && context.isStrict()) { 2693 return ~(position - 1); // minus zero not allowed 2694 } 2695 total = -total; 2696 } 2697 } else if (signStyle == SignStyle.EXCEEDS_PAD && context.isStrict()) { 2698 int parseLen = pos - position; 2699 if (positive) { 2700 if (parseLen <= minWidth) { 2701 return ~(position - 1); // '+' only parsed if minWidth exceeded 2702 } 2703 } else { 2704 if (parseLen > minWidth) { 2705 return ~position; // '+' must be parsed if minWidth exceeded 2706 } 2707 } 2708 } 2709 if (totalBig != null) { 2710 if (totalBig.bitLength() > 63) { 2711 // overflow, parse 1 less digit 2712 totalBig = totalBig.divide(BigInteger.TEN); 2713 pos--; 2714 } 2715 return setValue(context, totalBig.longValue(), position, pos); 2716 } 2717 return setValue(context, total, position, pos); 2718 } 2719 2720 /** 2721 * Stores the value. 2722 * 2723 * @param context the context to store into, not null 2724 * @param value the value 2725 * @param errorPos the position of the field being parsed 2726 * @param successPos the position after the field being parsed 2727 * @return the new position 2728 */ 2729 int setValue(DateTimeParseContext context, long value, int errorPos, int successPos) { 2730 return context.setParsedField(field, value, errorPos, successPos); 2731 } 2732 2733 @Override 2734 public String toString() { 2735 if (minWidth == 1 && maxWidth == 19 && signStyle == SignStyle.NORMAL) { 2736 return "Value(" + field + ")"; 2737 } 2738 if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) { 2739 return "Value(" + field + "," + minWidth + ")"; 2740 } 2741 return "Value(" + field + "," + minWidth + "," + maxWidth + "," + signStyle + ")"; 2742 } 2743 } 2744 2745 //----------------------------------------------------------------------- 2746 /** 2747 * Prints and parses a reduced numeric date-time field. 2748 */ 2749 static final class ReducedPrinterParser extends NumberPrinterParser { 2750 /** 2751 * The base date for reduced value parsing. 2752 */ 2753 static final LocalDate BASE_DATE = LocalDate.of(2000, 1, 1); 2754 2755 private final int baseValue; 2756 private final ChronoLocalDate baseDate; 2757 2758 /** 2759 * Constructor. 2760 * 2761 * @param field the field to format, validated not null 2762 * @param minWidth the minimum field width, from 1 to 10 2763 * @param maxWidth the maximum field width, from 1 to 10 2764 * @param baseValue the base value 2765 * @param baseDate the base date 2766 */ 2767 ReducedPrinterParser(TemporalField field, int minWidth, int maxWidth, 2768 int baseValue, ChronoLocalDate baseDate) { 2769 this(field, minWidth, maxWidth, baseValue, baseDate, 0); 2770 if (minWidth < 1 || minWidth > 10) { 2771 throw new IllegalArgumentException("The minWidth must be from 1 to 10 inclusive but was " + minWidth); 2772 } 2773 if (maxWidth < 1 || maxWidth > 10) { 2774 throw new IllegalArgumentException("The maxWidth must be from 1 to 10 inclusive but was " + minWidth); 2775 } 2776 if (maxWidth < minWidth) { 2777 throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " + 2778 maxWidth + " < " + minWidth); 2779 } 2780 if (baseDate == null) { 2781 if (field.range().isValidValue(baseValue) == false) { 2782 throw new IllegalArgumentException("The base value must be within the range of the field"); 2783 } 2784 if ((((long) baseValue) + EXCEED_POINTS[maxWidth]) > Integer.MAX_VALUE) { 2785 throw new DateTimeException("Unable to add printer-parser as the range exceeds the capacity of an int"); 2786 } 2787 } 2788 } 2789 2790 /** 2791 * Constructor. 2792 * The arguments have already been checked. 2793 * 2794 * @param field the field to format, validated not null 2795 * @param minWidth the minimum field width, from 1 to 10 2796 * @param maxWidth the maximum field width, from 1 to 10 2797 * @param baseValue the base value 2798 * @param baseDate the base date 2799 * @param subsequentWidth the subsequentWidth for this instance 2800 */ 2801 private ReducedPrinterParser(TemporalField field, int minWidth, int maxWidth, 2802 int baseValue, ChronoLocalDate baseDate, int subsequentWidth) { 2803 super(field, minWidth, maxWidth, SignStyle.NOT_NEGATIVE, subsequentWidth); 2804 this.baseValue = baseValue; 2805 this.baseDate = baseDate; 2806 } 2807 2808 @Override 2809 long getValue(DateTimePrintContext context, long value) { 2810 long absValue = Math.abs(value); 2811 int baseValue = this.baseValue; 2812 if (baseDate != null) { 2813 Chronology chrono = Chronology.from(context.getTemporal()); 2814 baseValue = chrono.date(baseDate).get(field); 2815 } 2816 if (value >= baseValue && value < baseValue + EXCEED_POINTS[minWidth]) { 2817 // Use the reduced value if it fits in minWidth 2818 return absValue % EXCEED_POINTS[minWidth]; 2819 } 2820 // Otherwise truncate to fit in maxWidth 2821 return absValue % EXCEED_POINTS[maxWidth]; 2822 } 2823 2824 @Override 2825 int setValue(DateTimeParseContext context, long value, int errorPos, int successPos) { 2826 int baseValue = this.baseValue; 2827 if (baseDate != null) { 2828 Chronology chrono = context.getEffectiveChronology(); 2829 baseValue = chrono.date(baseDate).get(field); 2830 2831 // In case the Chronology is changed later, add a callback when/if it changes 2832 final long initialValue = value; 2833 context.addChronoChangedListener( 2834 (_unused) -> { 2835 /* Repeat the set of the field using the current Chronology 2836 * The success/error position is ignored because the value is 2837 * intentionally being overwritten. 2838 */ 2839 setValue(context, initialValue, errorPos, successPos); 2840 }); 2841 } 2842 int parseLen = successPos - errorPos; 2843 if (parseLen == minWidth && value >= 0) { 2844 long range = EXCEED_POINTS[minWidth]; 2845 long lastPart = baseValue % range; 2846 long basePart = baseValue - lastPart; 2847 if (baseValue > 0) { 2848 value = basePart + value; 2849 } else { 2850 value = basePart - value; 2851 } 2852 if (value < baseValue) { 2853 value += range; 2854 } 2855 } 2856 return context.setParsedField(field, value, errorPos, successPos); 2857 } 2858 2859 /** 2860 * Returns a new instance with fixed width flag set. 2861 * 2862 * @return a new updated printer-parser, not null 2863 */ 2864 @Override 2865 ReducedPrinterParser withFixedWidth() { 2866 if (subsequentWidth == -1) { 2867 return this; 2868 } 2869 return new ReducedPrinterParser(field, minWidth, maxWidth, baseValue, baseDate, -1); 2870 } 2871 2872 /** 2873 * Returns a new instance with an updated subsequent width. 2874 * 2875 * @param subsequentWidth the width of subsequent non-negative numbers, 0 or greater 2876 * @return a new updated printer-parser, not null 2877 */ 2878 @Override 2879 ReducedPrinterParser withSubsequentWidth(int subsequentWidth) { 2880 return new ReducedPrinterParser(field, minWidth, maxWidth, baseValue, baseDate, 2881 this.subsequentWidth + subsequentWidth); 2882 } 2883 2884 /** 2885 * For a ReducedPrinterParser, fixed width is false if the mode is strict, 2886 * otherwise it is set as for NumberPrinterParser. 2887 * @param context the context 2888 * @return if the field is fixed width 2889 * @see DateTimeFormatterBuilder#appendValueReduced(java.time.temporal.TemporalField, int, int, int) 2890 */ 2891 @Override 2892 boolean isFixedWidth(DateTimeParseContext context) { 2893 if (context.isStrict() == false) { 2894 return false; 2895 } 2896 return super.isFixedWidth(context); 2897 } 2898 2899 @Override 2900 public String toString() { 2901 return "ReducedValue(" + field + "," + minWidth + "," + maxWidth + 2902 "," + Objects.requireNonNullElse(baseDate, baseValue) + ")"; 2903 } 2904 } 2905 2906 //----------------------------------------------------------------------- 2907 /** 2908 * Prints and parses a numeric date-time field with optional padding. 2909 */ 2910 static final class FractionPrinterParser implements DateTimePrinterParser { 2911 private final TemporalField field; 2912 private final int minWidth; 2913 private final int maxWidth; 2914 private final boolean decimalPoint; 2915 2916 /** 2917 * Constructor. 2918 * 2919 * @param field the field to output, not null 2920 * @param minWidth the minimum width to output, from 0 to 9 2921 * @param maxWidth the maximum width to output, from 0 to 9 2922 * @param decimalPoint whether to output the localized decimal point symbol 2923 */ 2924 FractionPrinterParser(TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) { 2925 Objects.requireNonNull(field, "field"); 2926 if (field.range().isFixed() == false) { 2927 throw new IllegalArgumentException("Field must have a fixed set of values: " + field); 2928 } 2929 if (minWidth < 0 || minWidth > 9) { 2930 throw new IllegalArgumentException("Minimum width must be from 0 to 9 inclusive but was " + minWidth); 2931 } 2932 if (maxWidth < 1 || maxWidth > 9) { 2933 throw new IllegalArgumentException("Maximum width must be from 1 to 9 inclusive but was " + maxWidth); 2934 } 2935 if (maxWidth < minWidth) { 2936 throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " + 2937 maxWidth + " < " + minWidth); 2938 } 2939 this.field = field; 2940 this.minWidth = minWidth; 2941 this.maxWidth = maxWidth; 2942 this.decimalPoint = decimalPoint; 2943 } 2944 2945 @Override 2946 public boolean format(DateTimePrintContext context, StringBuilder buf) { 2947 Long value = context.getValue(field); 2948 if (value == null) { 2949 return false; 2950 } 2951 DecimalStyle decimalStyle = context.getDecimalStyle(); 2952 BigDecimal fraction = convertToFraction(value); 2953 if (fraction.scale() == 0) { // scale is zero if value is zero 2954 if (minWidth > 0) { 2955 if (decimalPoint) { 2956 buf.append(decimalStyle.getDecimalSeparator()); 2957 } 2958 for (int i = 0; i < minWidth; i++) { 2959 buf.append(decimalStyle.getZeroDigit()); 2960 } 2961 } 2962 } else { 2963 int outputScale = Math.min(Math.max(fraction.scale(), minWidth), maxWidth); 2964 fraction = fraction.setScale(outputScale, RoundingMode.FLOOR); 2965 String str = fraction.toPlainString().substring(2); 2966 str = decimalStyle.convertNumberToI18N(str); 2967 if (decimalPoint) { 2968 buf.append(decimalStyle.getDecimalSeparator()); 2969 } 2970 buf.append(str); 2971 } 2972 return true; 2973 } 2974 2975 @Override 2976 public int parse(DateTimeParseContext context, CharSequence text, int position) { 2977 int effectiveMin = (context.isStrict() ? minWidth : 0); 2978 int effectiveMax = (context.isStrict() ? maxWidth : 9); 2979 int length = text.length(); 2980 if (position == length) { 2981 // valid if whole field is optional, invalid if minimum width 2982 return (effectiveMin > 0 ? ~position : position); 2983 } 2984 if (decimalPoint) { 2985 if (text.charAt(position) != context.getDecimalStyle().getDecimalSeparator()) { 2986 // valid if whole field is optional, invalid if minimum width 2987 return (effectiveMin > 0 ? ~position : position); 2988 } 2989 position++; 2990 } 2991 int minEndPos = position + effectiveMin; 2992 if (minEndPos > length) { 2993 return ~position; // need at least min width digits 2994 } 2995 int maxEndPos = Math.min(position + effectiveMax, length); 2996 int total = 0; // can use int because we are only parsing up to 9 digits 2997 int pos = position; 2998 while (pos < maxEndPos) { 2999 char ch = text.charAt(pos++); 3000 int digit = context.getDecimalStyle().convertToDigit(ch); 3001 if (digit < 0) { 3002 if (pos < minEndPos) { 3003 return ~position; // need at least min width digits 3004 } 3005 pos--; 3006 break; 3007 } 3008 total = total * 10 + digit; 3009 } 3010 BigDecimal fraction = new BigDecimal(total).movePointLeft(pos - position); 3011 long value = convertFromFraction(fraction); 3012 return context.setParsedField(field, value, position, pos); 3013 } 3014 3015 /** 3016 * Converts a value for this field to a fraction between 0 and 1. 3017 * <p> 3018 * The fractional value is between 0 (inclusive) and 1 (exclusive). 3019 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed. 3020 * The fraction is obtained by calculation from the field range using 9 decimal 3021 * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}. 3022 * The calculation is inaccurate if the values do not run continuously from smallest to largest. 3023 * <p> 3024 * For example, the second-of-minute value of 15 would be returned as 0.25, 3025 * assuming the standard definition of 60 seconds in a minute. 3026 * 3027 * @param value the value to convert, must be valid for this rule 3028 * @return the value as a fraction within the range, from 0 to 1, not null 3029 * @throws DateTimeException if the value cannot be converted to a fraction 3030 */ 3031 private BigDecimal convertToFraction(long value) { 3032 ValueRange range = field.range(); 3033 range.checkValidValue(value, field); 3034 BigDecimal minBD = BigDecimal.valueOf(range.getMinimum()); 3035 BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE); 3036 BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD); 3037 BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR); 3038 // stripTrailingZeros bug 3039 return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros(); 3040 } 3041 3042 /** 3043 * Converts a fraction from 0 to 1 for this field to a value. 3044 * <p> 3045 * The fractional value must be between 0 (inclusive) and 1 (exclusive). 3046 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed. 3047 * The value is obtained by calculation from the field range and a rounding 3048 * mode of {@link RoundingMode#FLOOR FLOOR}. 3049 * The calculation is inaccurate if the values do not run continuously from smallest to largest. 3050 * <p> 3051 * For example, the fractional second-of-minute of 0.25 would be converted to 15, 3052 * assuming the standard definition of 60 seconds in a minute. 3053 * 3054 * @param fraction the fraction to convert, not null 3055 * @return the value of the field, valid for this rule 3056 * @throws DateTimeException if the value cannot be converted 3057 */ 3058 private long convertFromFraction(BigDecimal fraction) { 3059 ValueRange range = field.range(); 3060 BigDecimal minBD = BigDecimal.valueOf(range.getMinimum()); 3061 BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE); 3062 BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD); 3063 return valueBD.longValueExact(); 3064 } 3065 3066 @Override 3067 public String toString() { 3068 String decimal = (decimalPoint ? ",DecimalPoint" : ""); 3069 return "Fraction(" + field + "," + minWidth + "," + maxWidth + decimal + ")"; 3070 } 3071 } 3072 3073 //----------------------------------------------------------------------- 3074 /** 3075 * Prints or parses field text. 3076 */ 3077 static final class TextPrinterParser implements DateTimePrinterParser { 3078 private final TemporalField field; 3079 private final TextStyle textStyle; 3080 private final DateTimeTextProvider provider; 3081 /** 3082 * The cached number printer parser. 3083 * Immutable and volatile, so no synchronization needed. 3084 */ 3085 private volatile NumberPrinterParser numberPrinterParser; 3086 3087 /** 3088 * Constructor. 3089 * 3090 * @param field the field to output, not null 3091 * @param textStyle the text style, not null 3092 * @param provider the text provider, not null 3093 */ 3094 TextPrinterParser(TemporalField field, TextStyle textStyle, DateTimeTextProvider provider) { 3095 // validated by caller 3096 this.field = field; 3097 this.textStyle = textStyle; 3098 this.provider = provider; 3099 } 3100 3101 @Override 3102 public boolean format(DateTimePrintContext context, StringBuilder buf) { 3103 Long value = context.getValue(field); 3104 if (value == null) { 3105 return false; 3106 } 3107 String text; 3108 Chronology chrono = context.getTemporal().query(TemporalQueries.chronology()); 3109 if (chrono == null || chrono == IsoChronology.INSTANCE) { 3110 text = provider.getText(field, value, textStyle, context.getLocale()); 3111 } else { 3112 text = provider.getText(chrono, field, value, textStyle, context.getLocale()); 3113 } 3114 if (text == null) { 3115 return numberPrinterParser().format(context, buf); 3116 } 3117 buf.append(text); 3118 return true; 3119 } 3120 3121 @Override 3122 public int parse(DateTimeParseContext context, CharSequence parseText, int position) { 3123 int length = parseText.length(); 3124 if (position < 0 || position > length) { 3125 throw new IndexOutOfBoundsException(); 3126 } 3127 TextStyle style = (context.isStrict() ? textStyle : null); 3128 Chronology chrono = context.getEffectiveChronology(); 3129 Iterator<Entry<String, Long>> it; 3130 if (chrono == null || chrono == IsoChronology.INSTANCE) { 3131 it = provider.getTextIterator(field, style, context.getLocale()); 3132 } else { 3133 it = provider.getTextIterator(chrono, field, style, context.getLocale()); 3134 } 3135 if (it != null) { 3136 while (it.hasNext()) { 3137 Entry<String, Long> entry = it.next(); 3138 String itText = entry.getKey(); 3139 if (context.subSequenceEquals(itText, 0, parseText, position, itText.length())) { 3140 return context.setParsedField(field, entry.getValue(), position, position + itText.length()); 3141 } 3142 } 3143 if (field == ERA && !context.isStrict()) { 3144 // parse the possible era name from era.toString() 3145 List<Era> eras = chrono.eras(); 3146 for (Era era : eras) { 3147 String name = era.toString(); 3148 if (context.subSequenceEquals(name, 0, parseText, position, name.length())) { 3149 return context.setParsedField(field, era.getValue(), position, position + name.length()); 3150 } 3151 } 3152 } 3153 if (context.isStrict()) { 3154 return ~position; 3155 } 3156 } 3157 return numberPrinterParser().parse(context, parseText, position); 3158 } 3159 3160 /** 3161 * Create and cache a number printer parser. 3162 * @return the number printer parser for this field, not null 3163 */ 3164 private NumberPrinterParser numberPrinterParser() { 3165 if (numberPrinterParser == null) { 3166 numberPrinterParser = new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL); 3167 } 3168 return numberPrinterParser; 3169 } 3170 3171 @Override 3172 public String toString() { 3173 if (textStyle == TextStyle.FULL) { 3174 return "Text(" + field + ")"; 3175 } 3176 return "Text(" + field + "," + textStyle + ")"; 3177 } 3178 } 3179 3180 //----------------------------------------------------------------------- 3181 /** 3182 * Prints or parses an ISO-8601 instant. 3183 */ 3184 static final class InstantPrinterParser implements DateTimePrinterParser { 3185 // days in a 400 year cycle = 146097 3186 // days in a 10,000 year cycle = 146097 * 25 3187 // seconds per day = 86400 3188 private static final long SECONDS_PER_10000_YEARS = 146097L * 25L * 86400L; 3189 private static final long SECONDS_0000_TO_1970 = ((146097L * 5L) - (30L * 365L + 7L)) * 86400L; 3190 private final int fractionalDigits; 3191 3192 InstantPrinterParser(int fractionalDigits) { 3193 this.fractionalDigits = fractionalDigits; 3194 } 3195 3196 @Override 3197 public boolean format(DateTimePrintContext context, StringBuilder buf) { 3198 // use INSTANT_SECONDS, thus this code is not bound by Instant.MAX 3199 Long inSecs = context.getValue(INSTANT_SECONDS); 3200 Long inNanos = null; 3201 if (context.getTemporal().isSupported(NANO_OF_SECOND)) { 3202 inNanos = context.getTemporal().getLong(NANO_OF_SECOND); 3203 } 3204 if (inSecs == null) { 3205 return false; 3206 } 3207 long inSec = inSecs; 3208 int inNano = NANO_OF_SECOND.checkValidIntValue(inNanos != null ? inNanos : 0); 3209 // format mostly using LocalDateTime.toString 3210 if (inSec >= -SECONDS_0000_TO_1970) { 3211 // current era 3212 long zeroSecs = inSec - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970; 3213 long hi = Math.floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1; 3214 long lo = Math.floorMod(zeroSecs, SECONDS_PER_10000_YEARS); 3215 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC); 3216 if (hi > 0) { 3217 buf.append('+').append(hi); 3218 } 3219 buf.append(ldt); 3220 if (ldt.getSecond() == 0) { 3221 buf.append(":00"); 3222 } 3223 } else { 3224 // before current era 3225 long zeroSecs = inSec + SECONDS_0000_TO_1970; 3226 long hi = zeroSecs / SECONDS_PER_10000_YEARS; 3227 long lo = zeroSecs % SECONDS_PER_10000_YEARS; 3228 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC); 3229 int pos = buf.length(); 3230 buf.append(ldt); 3231 if (ldt.getSecond() == 0) { 3232 buf.append(":00"); 3233 } 3234 if (hi < 0) { 3235 if (ldt.getYear() == -10_000) { 3236 buf.replace(pos, pos + 2, Long.toString(hi - 1)); 3237 } else if (lo == 0) { 3238 buf.insert(pos, hi); 3239 } else { 3240 buf.insert(pos + 1, Math.abs(hi)); 3241 } 3242 } 3243 } 3244 // add fraction 3245 if ((fractionalDigits < 0 && inNano > 0) || fractionalDigits > 0) { 3246 buf.append('.'); 3247 int div = 100_000_000; 3248 for (int i = 0; ((fractionalDigits == -1 && inNano > 0) || 3249 (fractionalDigits == -2 && (inNano > 0 || (i % 3) != 0)) || 3250 i < fractionalDigits); i++) { 3251 int digit = inNano / div; 3252 buf.append((char) (digit + '0')); 3253 inNano = inNano - (digit * div); 3254 div = div / 10; 3255 } 3256 } 3257 buf.append('Z'); 3258 return true; 3259 } 3260 3261 @Override 3262 public int parse(DateTimeParseContext context, CharSequence text, int position) { 3263 // new context to avoid overwriting fields like year/month/day 3264 int minDigits = (fractionalDigits < 0 ? 0 : fractionalDigits); 3265 int maxDigits = (fractionalDigits < 0 ? 9 : fractionalDigits); 3266 CompositePrinterParser parser = new DateTimeFormatterBuilder() 3267 .append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T') 3268 .appendValue(HOUR_OF_DAY, 2).appendLiteral(':') 3269 .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':') 3270 .appendValue(SECOND_OF_MINUTE, 2) 3271 .appendFraction(NANO_OF_SECOND, minDigits, maxDigits, true) 3272 .appendLiteral('Z') 3273 .toFormatter().toPrinterParser(false); 3274 DateTimeParseContext newContext = context.copy(); 3275 int pos = parser.parse(newContext, text, position); 3276 if (pos < 0) { 3277 return pos; 3278 } 3279 // parser restricts most fields to 2 digits, so definitely int 3280 // correctly parsed nano is also guaranteed to be valid 3281 long yearParsed = newContext.getParsed(YEAR); 3282 int month = newContext.getParsed(MONTH_OF_YEAR).intValue(); 3283 int day = newContext.getParsed(DAY_OF_MONTH).intValue(); 3284 int hour = newContext.getParsed(HOUR_OF_DAY).intValue(); 3285 int min = newContext.getParsed(MINUTE_OF_HOUR).intValue(); 3286 Long secVal = newContext.getParsed(SECOND_OF_MINUTE); 3287 Long nanoVal = newContext.getParsed(NANO_OF_SECOND); 3288 int sec = (secVal != null ? secVal.intValue() : 0); 3289 int nano = (nanoVal != null ? nanoVal.intValue() : 0); 3290 int days = 0; 3291 if (hour == 24 && min == 0 && sec == 0 && nano == 0) { 3292 hour = 0; 3293 days = 1; 3294 } else if (hour == 23 && min == 59 && sec == 60) { 3295 context.setParsedLeapSecond(); 3296 sec = 59; 3297 } 3298 int year = (int) yearParsed % 10_000; 3299 long instantSecs; 3300 try { 3301 LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, min, sec, 0).plusDays(days); 3302 instantSecs = ldt.toEpochSecond(ZoneOffset.UTC); 3303 instantSecs += Math.multiplyExact(yearParsed / 10_000L, SECONDS_PER_10000_YEARS); 3304 } catch (RuntimeException ex) { 3305 return ~position; 3306 } 3307 int successPos = pos; 3308 successPos = context.setParsedField(INSTANT_SECONDS, instantSecs, position, successPos); 3309 return context.setParsedField(NANO_OF_SECOND, nano, position, successPos); 3310 } 3311 3312 @Override 3313 public String toString() { 3314 return "Instant()"; 3315 } 3316 } 3317 3318 //----------------------------------------------------------------------- 3319 /** 3320 * Prints or parses an offset ID. 3321 */ 3322 static final class OffsetIdPrinterParser implements DateTimePrinterParser { 3323 static final String[] PATTERNS = new String[] { 3324 "+HH", "+HHmm", "+HH:mm", "+HHMM", "+HH:MM", "+HHMMss", "+HH:MM:ss", "+HHMMSS", "+HH:MM:SS", "+HHmmss", "+HH:mm:ss", 3325 }; // order used in pattern builder 3326 static final OffsetIdPrinterParser INSTANCE_ID_Z = new OffsetIdPrinterParser("+HH:MM:ss", "Z"); 3327 static final OffsetIdPrinterParser INSTANCE_ID_ZERO = new OffsetIdPrinterParser("+HH:MM:ss", "0"); 3328 3329 private final String noOffsetText; 3330 private final int type; 3331 3332 /** 3333 * Constructor. 3334 * 3335 * @param pattern the pattern 3336 * @param noOffsetText the text to use for UTC, not null 3337 */ 3338 OffsetIdPrinterParser(String pattern, String noOffsetText) { 3339 Objects.requireNonNull(pattern, "pattern"); 3340 Objects.requireNonNull(noOffsetText, "noOffsetText"); 3341 this.type = checkPattern(pattern); 3342 this.noOffsetText = noOffsetText; 3343 } 3344 3345 private int checkPattern(String pattern) { 3346 for (int i = 0; i < PATTERNS.length; i++) { 3347 if (PATTERNS[i].equals(pattern)) { 3348 return i; 3349 } 3350 } 3351 throw new IllegalArgumentException("Invalid zone offset pattern: " + pattern); 3352 } 3353 3354 @Override 3355 public boolean format(DateTimePrintContext context, StringBuilder buf) { 3356 Long offsetSecs = context.getValue(OFFSET_SECONDS); 3357 if (offsetSecs == null) { 3358 return false; 3359 } 3360 int totalSecs = Math.toIntExact(offsetSecs); 3361 if (totalSecs == 0) { 3362 buf.append(noOffsetText); 3363 } else { 3364 int absHours = Math.abs((totalSecs / 3600) % 100); // anything larger than 99 silently dropped 3365 int absMinutes = Math.abs((totalSecs / 60) % 60); 3366 int absSeconds = Math.abs(totalSecs % 60); 3367 int bufPos = buf.length(); 3368 int output = absHours; 3369 buf.append(totalSecs < 0 ? "-" : "+") 3370 .append((char) (absHours / 10 + '0')).append((char) (absHours % 10 + '0')); 3371 if ((type >= 3 && type < 9) || (type >= 9 && absSeconds > 0) || (type >= 1 && absMinutes > 0)) { 3372 buf.append((type % 2) == 0 ? ":" : "") 3373 .append((char) (absMinutes / 10 + '0')).append((char) (absMinutes % 10 + '0')); 3374 output += absMinutes; 3375 if (type == 7 || type == 8 || (type >= 5 && absSeconds > 0)) { 3376 buf.append((type % 2) == 0 ? ":" : "") 3377 .append((char) (absSeconds / 10 + '0')).append((char) (absSeconds % 10 + '0')); 3378 output += absSeconds; 3379 } 3380 } 3381 if (output == 0) { 3382 buf.setLength(bufPos); 3383 buf.append(noOffsetText); 3384 } 3385 } 3386 return true; 3387 } 3388 3389 @Override 3390 public int parse(DateTimeParseContext context, CharSequence text, int position) { 3391 int length = text.length(); 3392 int noOffsetLen = noOffsetText.length(); 3393 int parseType = type; 3394 if (context.isStrict() == false && type == 6) { 3395 parseType = 10; 3396 } else if (context.isStrict() == false && type == 5) { 3397 parseType = 9; 3398 } 3399 if (noOffsetLen == 0) { 3400 if (position == length) { 3401 return context.setParsedField(OFFSET_SECONDS, 0, position, position); 3402 } 3403 } else { 3404 if (position == length) { 3405 return ~position; 3406 } 3407 if (context.subSequenceEquals(text, position, noOffsetText, 0, noOffsetLen)) { 3408 return context.setParsedField(OFFSET_SECONDS, 0, position, position + noOffsetLen); 3409 } 3410 } 3411 3412 // parse normal plus/minus offset 3413 char sign = text.charAt(position); // IOOBE if invalid position 3414 if (sign == '+' || sign == '-') { 3415 // starts 3416 int negative = (sign == '-' ? -1 : 1); 3417 int[] array = new int[4]; 3418 array[0] = position + 1; 3419 if ((parseNumber(array, 1, text, true, parseType) || 3420 parseNumber(array, 2, text, parseType >= 3 && parseType < 9, parseType) || 3421 parseNumber(array, 3, text, type == 7 || type == 8, parseType)) == false) { 3422 // success 3423 long offsetSecs = negative * (array[1] * 3600L + array[2] * 60L + array[3]); 3424 return context.setParsedField(OFFSET_SECONDS, offsetSecs, position, array[0]); 3425 } 3426 } 3427 // handle special case of empty no offset text 3428 if (noOffsetLen == 0) { 3429 return context.setParsedField(OFFSET_SECONDS, 0, position, position); 3430 } 3431 return ~position; 3432 } 3433 3434 /** 3435 * Parse a two digit zero-prefixed number. 3436 * 3437 * @param array the array of parsed data, 0=pos,1=hours,2=mins,3=secs, not null 3438 * @param arrayIndex the index to parse the value into 3439 * @param parseText the offset ID, not null 3440 * @param required whether this number is required 3441 * @param parseType the offset pattern type 3442 * @return true if an error occurred 3443 */ 3444 private boolean parseNumber(int[] array, int arrayIndex, CharSequence parseText, boolean required, int parseType) { 3445 if ((parseType + 3) / 2 < arrayIndex) { 3446 return false; // ignore seconds/minutes 3447 } 3448 int pos = array[0]; 3449 if ((parseType % 2) == 0 && arrayIndex > 1) { 3450 if (pos + 1 > parseText.length() || parseText.charAt(pos) != ':') { 3451 return required; 3452 } 3453 pos++; 3454 } 3455 if (pos + 2 > parseText.length()) { 3456 return required; 3457 } 3458 char ch1 = parseText.charAt(pos++); 3459 char ch2 = parseText.charAt(pos++); 3460 if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') { 3461 return required; 3462 } 3463 int value = (ch1 - 48) * 10 + (ch2 - 48); 3464 if (value < 0 || value > 59) { 3465 return required; 3466 } 3467 array[arrayIndex] = value; 3468 array[0] = pos; 3469 return false; 3470 } 3471 3472 @Override 3473 public String toString() { 3474 String converted = noOffsetText.replace("'", "''"); 3475 return "Offset(" + PATTERNS[type] + ",'" + converted + "')"; 3476 } 3477 } 3478 3479 //----------------------------------------------------------------------- 3480 /** 3481 * Prints or parses an offset ID. 3482 */ 3483 static final class LocalizedOffsetIdPrinterParser implements DateTimePrinterParser { 3484 private final TextStyle style; 3485 3486 /** 3487 * Constructor. 3488 * 3489 * @param style the style, not null 3490 */ 3491 LocalizedOffsetIdPrinterParser(TextStyle style) { 3492 this.style = style; 3493 } 3494 3495 private static StringBuilder appendHMS(StringBuilder buf, int t) { 3496 return buf.append((char)(t / 10 + '0')) 3497 .append((char)(t % 10 + '0')); 3498 } 3499 3500 @Override 3501 public boolean format(DateTimePrintContext context, StringBuilder buf) { 3502 Long offsetSecs = context.getValue(OFFSET_SECONDS); 3503 if (offsetSecs == null) { 3504 return false; 3505 } 3506 String gmtText = "GMT"; // TODO: get localized version of 'GMT' 3507 if (gmtText != null) { 3508 buf.append(gmtText); 3509 } 3510 int totalSecs = Math.toIntExact(offsetSecs); 3511 if (totalSecs != 0) { 3512 int absHours = Math.abs((totalSecs / 3600) % 100); // anything larger than 99 silently dropped 3513 int absMinutes = Math.abs((totalSecs / 60) % 60); 3514 int absSeconds = Math.abs(totalSecs % 60); 3515 buf.append(totalSecs < 0 ? "-" : "+"); 3516 if (style == TextStyle.FULL) { 3517 appendHMS(buf, absHours); 3518 buf.append(':'); 3519 appendHMS(buf, absMinutes); 3520 if (absSeconds != 0) { 3521 buf.append(':'); 3522 appendHMS(buf, absSeconds); 3523 } 3524 } else { 3525 if (absHours >= 10) { 3526 buf.append((char)(absHours / 10 + '0')); 3527 } 3528 buf.append((char)(absHours % 10 + '0')); 3529 if (absMinutes != 0 || absSeconds != 0) { 3530 buf.append(':'); 3531 appendHMS(buf, absMinutes); 3532 if (absSeconds != 0) { 3533 buf.append(':'); 3534 appendHMS(buf, absSeconds); 3535 } 3536 } 3537 } 3538 } 3539 return true; 3540 } 3541 3542 int getDigit(CharSequence text, int position) { 3543 char c = text.charAt(position); 3544 if (c < '0' || c > '9') { 3545 return -1; 3546 } 3547 return c - '0'; 3548 } 3549 3550 @Override 3551 public int parse(DateTimeParseContext context, CharSequence text, int position) { 3552 int pos = position; 3553 int end = pos + text.length(); 3554 String gmtText = "GMT"; // TODO: get localized version of 'GMT' 3555 if (gmtText != null) { 3556 if (!context.subSequenceEquals(text, pos, gmtText, 0, gmtText.length())) { 3557 return ~position; 3558 } 3559 pos += gmtText.length(); 3560 } 3561 // parse normal plus/minus offset 3562 int negative = 0; 3563 if (pos == end) { 3564 return context.setParsedField(OFFSET_SECONDS, 0, position, pos); 3565 } 3566 char sign = text.charAt(pos); // IOOBE if invalid position 3567 if (sign == '+') { 3568 negative = 1; 3569 } else if (sign == '-') { 3570 negative = -1; 3571 } else { 3572 return context.setParsedField(OFFSET_SECONDS, 0, position, pos); 3573 } 3574 pos++; 3575 int h = 0; 3576 int m = 0; 3577 int s = 0; 3578 if (style == TextStyle.FULL) { 3579 int h1 = getDigit(text, pos++); 3580 int h2 = getDigit(text, pos++); 3581 if (h1 < 0 || h2 < 0 || text.charAt(pos++) != ':') { 3582 return ~position; 3583 } 3584 h = h1 * 10 + h2; 3585 int m1 = getDigit(text, pos++); 3586 int m2 = getDigit(text, pos++); 3587 if (m1 < 0 || m2 < 0) { 3588 return ~position; 3589 } 3590 m = m1 * 10 + m2; 3591 if (pos + 2 < end && text.charAt(pos) == ':') { 3592 int s1 = getDigit(text, pos + 1); 3593 int s2 = getDigit(text, pos + 2); 3594 if (s1 >= 0 && s2 >= 0) { 3595 s = s1 * 10 + s2; 3596 pos += 3; 3597 } 3598 } 3599 } else { 3600 h = getDigit(text, pos++); 3601 if (h < 0) { 3602 return ~position; 3603 } 3604 if (pos < end) { 3605 int h2 = getDigit(text, pos); 3606 if (h2 >=0) { 3607 h = h * 10 + h2; 3608 pos++; 3609 } 3610 if (pos + 2 < end && text.charAt(pos) == ':') { 3611 if (pos + 2 < end && text.charAt(pos) == ':') { 3612 int m1 = getDigit(text, pos + 1); 3613 int m2 = getDigit(text, pos + 2); 3614 if (m1 >= 0 && m2 >= 0) { 3615 m = m1 * 10 + m2; 3616 pos += 3; 3617 if (pos + 2 < end && text.charAt(pos) == ':') { 3618 int s1 = getDigit(text, pos + 1); 3619 int s2 = getDigit(text, pos + 2); 3620 if (s1 >= 0 && s2 >= 0) { 3621 s = s1 * 10 + s2; 3622 pos += 3; 3623 } 3624 } 3625 } 3626 } 3627 } 3628 } 3629 } 3630 long offsetSecs = negative * (h * 3600L + m * 60L + s); 3631 return context.setParsedField(OFFSET_SECONDS, offsetSecs, position, pos); 3632 } 3633 3634 @Override 3635 public String toString() { 3636 return "LocalizedOffset(" + style + ")"; 3637 } 3638 } 3639 3640 //----------------------------------------------------------------------- 3641 /** 3642 * Prints or parses a zone ID. 3643 */ 3644 static final class ZoneTextPrinterParser extends ZoneIdPrinterParser { 3645 3646 /** The text style to output. */ 3647 private final TextStyle textStyle; 3648 3649 /** The preferred zoneid map */ 3650 private Set<String> preferredZones; 3651 3652 ZoneTextPrinterParser(TextStyle textStyle, Set<ZoneId> preferredZones) { 3653 super(TemporalQueries.zone(), "ZoneText(" + textStyle + ")"); 3654 this.textStyle = Objects.requireNonNull(textStyle, "textStyle"); 3655 if (preferredZones != null && preferredZones.size() != 0) { 3656 this.preferredZones = new HashSet<>(); 3657 for (ZoneId id : preferredZones) { 3658 this.preferredZones.add(id.getId()); 3659 } 3660 } 3661 } 3662 3663 private static final int STD = 0; 3664 private static final int DST = 1; 3665 private static final int GENERIC = 2; 3666 private static final Map<String, SoftReference<Map<Locale, String[]>>> cache = 3667 new ConcurrentHashMap<>(); 3668 3669 private String getDisplayName(String id, int type, Locale locale) { 3670 if (textStyle == TextStyle.NARROW) { 3671 return null; 3672 } 3673 String[] names; 3674 SoftReference<Map<Locale, String[]>> ref = cache.get(id); 3675 Map<Locale, String[]> perLocale = null; 3676 if (ref == null || (perLocale = ref.get()) == null || 3677 (names = perLocale.get(locale)) == null) { 3678 names = TimeZoneNameUtility.retrieveDisplayNames(id, locale); 3679 if (names == null) { 3680 return null; 3681 } 3682 names = Arrays.copyOfRange(names, 0, 7); 3683 names[5] = 3684 TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.LONG, locale); 3685 if (names[5] == null) { 3686 names[5] = names[0]; // use the id 3687 } 3688 names[6] = 3689 TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.SHORT, locale); 3690 if (names[6] == null) { 3691 names[6] = names[0]; 3692 } 3693 if (perLocale == null) { 3694 perLocale = new ConcurrentHashMap<>(); 3695 } 3696 perLocale.put(locale, names); 3697 cache.put(id, new SoftReference<>(perLocale)); 3698 } 3699 switch (type) { 3700 case STD: 3701 return names[textStyle.zoneNameStyleIndex() + 1]; 3702 case DST: 3703 return names[textStyle.zoneNameStyleIndex() + 3]; 3704 } 3705 return names[textStyle.zoneNameStyleIndex() + 5]; 3706 } 3707 3708 @Override 3709 public boolean format(DateTimePrintContext context, StringBuilder buf) { 3710 ZoneId zone = context.getValue(TemporalQueries.zoneId()); 3711 if (zone == null) { 3712 return false; 3713 } 3714 String zname = zone.getId(); 3715 if (!(zone instanceof ZoneOffset)) { 3716 TemporalAccessor dt = context.getTemporal(); 3717 String name = getDisplayName(zname, 3718 dt.isSupported(ChronoField.INSTANT_SECONDS) 3719 ? (zone.getRules().isDaylightSavings(Instant.from(dt)) ? DST : STD) 3720 : GENERIC, 3721 context.getLocale()); 3722 if (name != null) { 3723 zname = name; 3724 } 3725 } 3726 buf.append(zname); 3727 return true; 3728 } 3729 3730 // cache per instance for now 3731 private final Map<Locale, Entry<Integer, SoftReference<PrefixTree>>> 3732 cachedTree = new HashMap<>(); 3733 private final Map<Locale, Entry<Integer, SoftReference<PrefixTree>>> 3734 cachedTreeCI = new HashMap<>(); 3735 3736 @Override 3737 protected PrefixTree getTree(DateTimeParseContext context) { 3738 if (textStyle == TextStyle.NARROW) { 3739 return super.getTree(context); 3740 } 3741 Locale locale = context.getLocale(); 3742 boolean isCaseSensitive = context.isCaseSensitive(); 3743 Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds(); 3744 int regionIdsSize = regionIds.size(); 3745 3746 Map<Locale, Entry<Integer, SoftReference<PrefixTree>>> cached = 3747 isCaseSensitive ? cachedTree : cachedTreeCI; 3748 3749 Entry<Integer, SoftReference<PrefixTree>> entry = null; 3750 PrefixTree tree = null; 3751 String[][] zoneStrings = null; 3752 if ((entry = cached.get(locale)) == null || 3753 (entry.getKey() != regionIdsSize || 3754 (tree = entry.getValue().get()) == null)) { 3755 tree = PrefixTree.newTree(context); 3756 zoneStrings = TimeZoneNameUtility.getZoneStrings(locale); 3757 for (String[] names : zoneStrings) { 3758 String zid = names[0]; 3759 if (!regionIds.contains(zid)) { 3760 continue; 3761 } 3762 tree.add(zid, zid); // don't convert zid -> metazone 3763 zid = ZoneName.toZid(zid, locale); 3764 int i = textStyle == TextStyle.FULL ? 1 : 2; 3765 for (; i < names.length; i += 2) { 3766 tree.add(names[i], zid); 3767 } 3768 } 3769 // if we have a set of preferred zones, need a copy and 3770 // add the preferred zones again to overwrite 3771 if (preferredZones != null) { 3772 for (String[] names : zoneStrings) { 3773 String zid = names[0]; 3774 if (!preferredZones.contains(zid) || !regionIds.contains(zid)) { 3775 continue; 3776 } 3777 int i = textStyle == TextStyle.FULL ? 1 : 2; 3778 for (; i < names.length; i += 2) { 3779 tree.add(names[i], zid); 3780 } 3781 } 3782 } 3783 cached.put(locale, new SimpleImmutableEntry<>(regionIdsSize, new SoftReference<>(tree))); 3784 } 3785 return tree; 3786 } 3787 } 3788 3789 //----------------------------------------------------------------------- 3790 /** 3791 * Prints or parses a zone ID. 3792 */ 3793 static class ZoneIdPrinterParser implements DateTimePrinterParser { 3794 private final TemporalQuery<ZoneId> query; 3795 private final String description; 3796 3797 ZoneIdPrinterParser(TemporalQuery<ZoneId> query, String description) { 3798 this.query = query; 3799 this.description = description; 3800 } 3801 3802 @Override 3803 public boolean format(DateTimePrintContext context, StringBuilder buf) { 3804 ZoneId zone = context.getValue(query); 3805 if (zone == null) { 3806 return false; 3807 } 3808 buf.append(zone.getId()); 3809 return true; 3810 } 3811 3812 /** 3813 * The cached tree to speed up parsing. 3814 */ 3815 private static volatile Entry<Integer, PrefixTree> cachedPrefixTree; 3816 private static volatile Entry<Integer, PrefixTree> cachedPrefixTreeCI; 3817 3818 protected PrefixTree getTree(DateTimeParseContext context) { 3819 // prepare parse tree 3820 Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds(); 3821 final int regionIdsSize = regionIds.size(); 3822 Entry<Integer, PrefixTree> cached = context.isCaseSensitive() 3823 ? cachedPrefixTree : cachedPrefixTreeCI; 3824 if (cached == null || cached.getKey() != regionIdsSize) { 3825 synchronized (this) { 3826 cached = context.isCaseSensitive() ? cachedPrefixTree : cachedPrefixTreeCI; 3827 if (cached == null || cached.getKey() != regionIdsSize) { 3828 cached = new SimpleImmutableEntry<>(regionIdsSize, PrefixTree.newTree(regionIds, context)); 3829 if (context.isCaseSensitive()) { 3830 cachedPrefixTree = cached; 3831 } else { 3832 cachedPrefixTreeCI = cached; 3833 } 3834 } 3835 } 3836 } 3837 return cached.getValue(); 3838 } 3839 3840 /** 3841 * This implementation looks for the longest matching string. 3842 * For example, parsing Etc/GMT-2 will return Etc/GMC-2 rather than just 3843 * Etc/GMC although both are valid. 3844 */ 3845 @Override 3846 public int parse(DateTimeParseContext context, CharSequence text, int position) { 3847 int length = text.length(); 3848 if (position > length) { 3849 throw new IndexOutOfBoundsException(); 3850 } 3851 if (position == length) { 3852 return ~position; 3853 } 3854 3855 // handle fixed time-zone IDs 3856 char nextChar = text.charAt(position); 3857 if (nextChar == '+' || nextChar == '-') { 3858 return parseOffsetBased(context, text, position, position, OffsetIdPrinterParser.INSTANCE_ID_Z); 3859 } else if (length >= position + 2) { 3860 char nextNextChar = text.charAt(position + 1); 3861 if (context.charEquals(nextChar, 'U') && context.charEquals(nextNextChar, 'T')) { 3862 if (length >= position + 3 && context.charEquals(text.charAt(position + 2), 'C')) { 3863 return parseOffsetBased(context, text, position, position + 3, OffsetIdPrinterParser.INSTANCE_ID_ZERO); 3864 } 3865 return parseOffsetBased(context, text, position, position + 2, OffsetIdPrinterParser.INSTANCE_ID_ZERO); 3866 } else if (context.charEquals(nextChar, 'G') && length >= position + 3 && 3867 context.charEquals(nextNextChar, 'M') && context.charEquals(text.charAt(position + 2), 'T')) { 3868 if (length >= position + 4 && context.charEquals(text.charAt(position + 3), '0')) { 3869 context.setParsed(ZoneId.of("GMT0")); 3870 return position + 4; 3871 } 3872 return parseOffsetBased(context, text, position, position + 3, OffsetIdPrinterParser.INSTANCE_ID_ZERO); 3873 } 3874 } 3875 3876 // parse 3877 PrefixTree tree = getTree(context); 3878 ParsePosition ppos = new ParsePosition(position); 3879 String parsedZoneId = tree.match(text, ppos); 3880 if (parsedZoneId == null) { 3881 if (context.charEquals(nextChar, 'Z')) { 3882 context.setParsed(ZoneOffset.UTC); 3883 return position + 1; 3884 } 3885 return ~position; 3886 } 3887 context.setParsed(ZoneId.of(parsedZoneId)); 3888 return ppos.getIndex(); 3889 } 3890 3891 /** 3892 * Parse an offset following a prefix and set the ZoneId if it is valid. 3893 * To matching the parsing of ZoneId.of the values are not normalized 3894 * to ZoneOffsets. 3895 * 3896 * @param context the parse context 3897 * @param text the input text 3898 * @param prefixPos start of the prefix 3899 * @param position start of text after the prefix 3900 * @param parser parser for the value after the prefix 3901 * @return the position after the parse 3902 */ 3903 private int parseOffsetBased(DateTimeParseContext context, CharSequence text, int prefixPos, int position, OffsetIdPrinterParser parser) { 3904 String prefix = text.toString().substring(prefixPos, position).toUpperCase(); 3905 if (position >= text.length()) { 3906 context.setParsed(ZoneId.of(prefix)); 3907 return position; 3908 } 3909 3910 // '0' or 'Z' after prefix is not part of a valid ZoneId; use bare prefix 3911 if (text.charAt(position) == '0' || 3912 context.charEquals(text.charAt(position), 'Z')) { 3913 context.setParsed(ZoneId.of(prefix)); 3914 return position; 3915 } 3916 3917 DateTimeParseContext newContext = context.copy(); 3918 int endPos = parser.parse(newContext, text, position); 3919 try { 3920 if (endPos < 0) { 3921 if (parser == OffsetIdPrinterParser.INSTANCE_ID_Z) { 3922 return ~prefixPos; 3923 } 3924 context.setParsed(ZoneId.of(prefix)); 3925 return position; 3926 } 3927 int offset = (int) newContext.getParsed(OFFSET_SECONDS).longValue(); 3928 ZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(offset); 3929 context.setParsed(ZoneId.ofOffset(prefix, zoneOffset)); 3930 return endPos; 3931 } catch (DateTimeException dte) { 3932 return ~prefixPos; 3933 } 3934 } 3935 3936 @Override 3937 public String toString() { 3938 return description; 3939 } 3940 } 3941 3942 //----------------------------------------------------------------------- 3943 /** 3944 * A String based prefix tree for parsing time-zone names. 3945 */ 3946 static class PrefixTree { 3947 protected String key; 3948 protected String value; 3949 protected char c0; // performance optimization to avoid the 3950 // boundary check cost of key.charat(0) 3951 protected PrefixTree child; 3952 protected PrefixTree sibling; 3953 3954 private PrefixTree(String k, String v, PrefixTree child) { 3955 this.key = k; 3956 this.value = v; 3957 this.child = child; 3958 if (k.length() == 0){ 3959 c0 = 0xffff; 3960 } else { 3961 c0 = key.charAt(0); 3962 } 3963 } 3964 3965 /** 3966 * Creates a new prefix parsing tree based on parse context. 3967 * 3968 * @param context the parse context 3969 * @return the tree, not null 3970 */ 3971 public static PrefixTree newTree(DateTimeParseContext context) { 3972 //if (!context.isStrict()) { 3973 // return new LENIENT("", null, null); 3974 //} 3975 if (context.isCaseSensitive()) { 3976 return new PrefixTree("", null, null); 3977 } 3978 return new CI("", null, null); 3979 } 3980 3981 /** 3982 * Creates a new prefix parsing tree. 3983 * 3984 * @param keys a set of strings to build the prefix parsing tree, not null 3985 * @param context the parse context 3986 * @return the tree, not null 3987 */ 3988 public static PrefixTree newTree(Set<String> keys, DateTimeParseContext context) { 3989 PrefixTree tree = newTree(context); 3990 for (String k : keys) { 3991 tree.add0(k, k); 3992 } 3993 return tree; 3994 } 3995 3996 /** 3997 * Clone a copy of this tree 3998 */ 3999 public PrefixTree copyTree() { 4000 PrefixTree copy = new PrefixTree(key, value, null); 4001 if (child != null) { 4002 copy.child = child.copyTree(); 4003 } 4004 if (sibling != null) { 4005 copy.sibling = sibling.copyTree(); 4006 } 4007 return copy; 4008 } 4009 4010 4011 /** 4012 * Adds a pair of {key, value} into the prefix tree. 4013 * 4014 * @param k the key, not null 4015 * @param v the value, not null 4016 * @return true if the pair is added successfully 4017 */ 4018 public boolean add(String k, String v) { 4019 return add0(k, v); 4020 } 4021 4022 private boolean add0(String k, String v) { 4023 k = toKey(k); 4024 int prefixLen = prefixLength(k); 4025 if (prefixLen == key.length()) { 4026 if (prefixLen < k.length()) { // down the tree 4027 String subKey = k.substring(prefixLen); 4028 PrefixTree c = child; 4029 while (c != null) { 4030 if (isEqual(c.c0, subKey.charAt(0))) { 4031 return c.add0(subKey, v); 4032 } 4033 c = c.sibling; 4034 } 4035 // add the node as the child of the current node 4036 c = newNode(subKey, v, null); 4037 c.sibling = child; 4038 child = c; 4039 return true; 4040 } 4041 // have an existing <key, value> already, overwrite it 4042 // if (value != null) { 4043 // return false; 4044 //} 4045 value = v; 4046 return true; 4047 } 4048 // split the existing node 4049 PrefixTree n1 = newNode(key.substring(prefixLen), value, child); 4050 key = k.substring(0, prefixLen); 4051 child = n1; 4052 if (prefixLen < k.length()) { 4053 PrefixTree n2 = newNode(k.substring(prefixLen), v, null); 4054 child.sibling = n2; 4055 value = null; 4056 } else { 4057 value = v; 4058 } 4059 return true; 4060 } 4061 4062 /** 4063 * Match text with the prefix tree. 4064 * 4065 * @param text the input text to parse, not null 4066 * @param off the offset position to start parsing at 4067 * @param end the end position to stop parsing 4068 * @return the resulting string, or null if no match found. 4069 */ 4070 public String match(CharSequence text, int off, int end) { 4071 if (!prefixOf(text, off, end)){ 4072 return null; 4073 } 4074 if (child != null && (off += key.length()) != end) { 4075 PrefixTree c = child; 4076 do { 4077 if (isEqual(c.c0, text.charAt(off))) { 4078 String found = c.match(text, off, end); 4079 if (found != null) { 4080 return found; 4081 } 4082 return value; 4083 } 4084 c = c.sibling; 4085 } while (c != null); 4086 } 4087 return value; 4088 } 4089 4090 /** 4091 * Match text with the prefix tree. 4092 * 4093 * @param text the input text to parse, not null 4094 * @param pos the position to start parsing at, from 0 to the text 4095 * length. Upon return, position will be updated to the new parse 4096 * position, or unchanged, if no match found. 4097 * @return the resulting string, or null if no match found. 4098 */ 4099 public String match(CharSequence text, ParsePosition pos) { 4100 int off = pos.getIndex(); 4101 int end = text.length(); 4102 if (!prefixOf(text, off, end)){ 4103 return null; 4104 } 4105 off += key.length(); 4106 if (child != null && off != end) { 4107 PrefixTree c = child; 4108 do { 4109 if (isEqual(c.c0, text.charAt(off))) { 4110 pos.setIndex(off); 4111 String found = c.match(text, pos); 4112 if (found != null) { 4113 return found; 4114 } 4115 break; 4116 } 4117 c = c.sibling; 4118 } while (c != null); 4119 } 4120 pos.setIndex(off); 4121 return value; 4122 } 4123 4124 protected String toKey(String k) { 4125 return k; 4126 } 4127 4128 protected PrefixTree newNode(String k, String v, PrefixTree child) { 4129 return new PrefixTree(k, v, child); 4130 } 4131 4132 protected boolean isEqual(char c1, char c2) { 4133 return c1 == c2; 4134 } 4135 4136 protected boolean prefixOf(CharSequence text, int off, int end) { 4137 if (text instanceof String) { 4138 return ((String)text).startsWith(key, off); 4139 } 4140 int len = key.length(); 4141 if (len > end - off) { 4142 return false; 4143 } 4144 int off0 = 0; 4145 while (len-- > 0) { 4146 if (!isEqual(key.charAt(off0++), text.charAt(off++))) { 4147 return false; 4148 } 4149 } 4150 return true; 4151 } 4152 4153 private int prefixLength(String k) { 4154 int off = 0; 4155 while (off < k.length() && off < key.length()) { 4156 if (!isEqual(k.charAt(off), key.charAt(off))) { 4157 return off; 4158 } 4159 off++; 4160 } 4161 return off; 4162 } 4163 4164 /** 4165 * Case Insensitive prefix tree. 4166 */ 4167 private static class CI extends PrefixTree { 4168 4169 private CI(String k, String v, PrefixTree child) { 4170 super(k, v, child); 4171 } 4172 4173 @Override 4174 protected CI newNode(String k, String v, PrefixTree child) { 4175 return new CI(k, v, child); 4176 } 4177 4178 @Override 4179 protected boolean isEqual(char c1, char c2) { 4180 return DateTimeParseContext.charEqualsIgnoreCase(c1, c2); 4181 } 4182 4183 @Override 4184 protected boolean prefixOf(CharSequence text, int off, int end) { 4185 int len = key.length(); 4186 if (len > end - off) { 4187 return false; 4188 } 4189 int off0 = 0; 4190 while (len-- > 0) { 4191 if (!isEqual(key.charAt(off0++), text.charAt(off++))) { 4192 return false; 4193 } 4194 } 4195 return true; 4196 } 4197 } 4198 4199 /** 4200 * Lenient prefix tree. Case insensitive and ignores characters 4201 * like space, underscore and slash. 4202 */ 4203 private static class LENIENT extends CI { 4204 4205 private LENIENT(String k, String v, PrefixTree child) { 4206 super(k, v, child); 4207 } 4208 4209 @Override 4210 protected CI newNode(String k, String v, PrefixTree child) { 4211 return new LENIENT(k, v, child); 4212 } 4213 4214 private boolean isLenientChar(char c) { 4215 return c == ' ' || c == '_' || c == '/'; 4216 } 4217 4218 protected String toKey(String k) { 4219 for (int i = 0; i < k.length(); i++) { 4220 if (isLenientChar(k.charAt(i))) { 4221 StringBuilder sb = new StringBuilder(k.length()); 4222 sb.append(k, 0, i); 4223 i++; 4224 while (i < k.length()) { 4225 if (!isLenientChar(k.charAt(i))) { 4226 sb.append(k.charAt(i)); 4227 } 4228 i++; 4229 } 4230 return sb.toString(); 4231 } 4232 } 4233 return k; 4234 } 4235 4236 @Override 4237 public String match(CharSequence text, ParsePosition pos) { 4238 int off = pos.getIndex(); 4239 int end = text.length(); 4240 int len = key.length(); 4241 int koff = 0; 4242 while (koff < len && off < end) { 4243 if (isLenientChar(text.charAt(off))) { 4244 off++; 4245 continue; 4246 } 4247 if (!isEqual(key.charAt(koff++), text.charAt(off++))) { 4248 return null; 4249 } 4250 } 4251 if (koff != len) { 4252 return null; 4253 } 4254 if (child != null && off != end) { 4255 int off0 = off; 4256 while (off0 < end && isLenientChar(text.charAt(off0))) { 4257 off0++; 4258 } 4259 if (off0 < end) { 4260 PrefixTree c = child; 4261 do { 4262 if (isEqual(c.c0, text.charAt(off0))) { 4263 pos.setIndex(off0); 4264 String found = c.match(text, pos); 4265 if (found != null) { 4266 return found; 4267 } 4268 break; 4269 } 4270 c = c.sibling; 4271 } while (c != null); 4272 } 4273 } 4274 pos.setIndex(off); 4275 return value; 4276 } 4277 } 4278 } 4279 4280 //----------------------------------------------------------------------- 4281 /** 4282 * Prints or parses a chronology. 4283 */ 4284 static final class ChronoPrinterParser implements DateTimePrinterParser { 4285 /** The text style to output, null means the ID. */ 4286 private final TextStyle textStyle; 4287 4288 ChronoPrinterParser(TextStyle textStyle) { 4289 // validated by caller 4290 this.textStyle = textStyle; 4291 } 4292 4293 @Override 4294 public boolean format(DateTimePrintContext context, StringBuilder buf) { 4295 Chronology chrono = context.getValue(TemporalQueries.chronology()); 4296 if (chrono == null) { 4297 return false; 4298 } 4299 if (textStyle == null) { 4300 buf.append(chrono.getId()); 4301 } else { 4302 buf.append(getChronologyName(chrono, context.getLocale())); 4303 } 4304 return true; 4305 } 4306 4307 @Override 4308 public int parse(DateTimeParseContext context, CharSequence text, int position) { 4309 // simple looping parser to find the chronology 4310 if (position < 0 || position > text.length()) { 4311 throw new IndexOutOfBoundsException(); 4312 } 4313 Set<Chronology> chronos = Chronology.getAvailableChronologies(); 4314 Chronology bestMatch = null; 4315 int matchLen = -1; 4316 for (Chronology chrono : chronos) { 4317 String name; 4318 if (textStyle == null) { 4319 name = chrono.getId(); 4320 } else { 4321 name = getChronologyName(chrono, context.getLocale()); 4322 } 4323 int nameLen = name.length(); 4324 if (nameLen > matchLen && context.subSequenceEquals(text, position, name, 0, nameLen)) { 4325 bestMatch = chrono; 4326 matchLen = nameLen; 4327 } 4328 } 4329 if (bestMatch == null) { 4330 return ~position; 4331 } 4332 context.setParsed(bestMatch); 4333 return position + matchLen; 4334 } 4335 4336 /** 4337 * Returns the chronology name of the given chrono in the given locale 4338 * if available, or the chronology Id otherwise. The regular ResourceBundle 4339 * search path is used for looking up the chronology name. 4340 * 4341 * @param chrono the chronology, not null 4342 * @param locale the locale, not null 4343 * @return the chronology name of chrono in locale, or the id if no name is available 4344 * @throws NullPointerException if chrono or locale is null 4345 */ 4346 private String getChronologyName(Chronology chrono, Locale locale) { 4347 String key = "calendarname." + chrono.getCalendarType(); 4348 String name = DateTimeTextProvider.getLocalizedResource(key, locale); 4349 return Objects.requireNonNullElseGet(name, () -> chrono.getId()); 4350 } 4351 } 4352 4353 //----------------------------------------------------------------------- 4354 /** 4355 * Prints or parses a localized pattern. 4356 */ 4357 static final class LocalizedPrinterParser implements DateTimePrinterParser { 4358 /** Cache of formatters. */ 4359 private static final ConcurrentMap<String, DateTimeFormatter> FORMATTER_CACHE = new ConcurrentHashMap<>(16, 0.75f, 2); 4360 4361 private final FormatStyle dateStyle; 4362 private final FormatStyle timeStyle; 4363 4364 /** 4365 * Constructor. 4366 * 4367 * @param dateStyle the date style to use, may be null 4368 * @param timeStyle the time style to use, may be null 4369 */ 4370 LocalizedPrinterParser(FormatStyle dateStyle, FormatStyle timeStyle) { 4371 // validated by caller 4372 this.dateStyle = dateStyle; 4373 this.timeStyle = timeStyle; 4374 } 4375 4376 @Override 4377 public boolean format(DateTimePrintContext context, StringBuilder buf) { 4378 Chronology chrono = Chronology.from(context.getTemporal()); 4379 return formatter(context.getLocale(), chrono).toPrinterParser(false).format(context, buf); 4380 } 4381 4382 @Override 4383 public int parse(DateTimeParseContext context, CharSequence text, int position) { 4384 Chronology chrono = context.getEffectiveChronology(); 4385 return formatter(context.getLocale(), chrono).toPrinterParser(false).parse(context, text, position); 4386 } 4387 4388 /** 4389 * Gets the formatter to use. 4390 * <p> 4391 * The formatter will be the most appropriate to use for the date and time style in the locale. 4392 * For example, some locales will use the month name while others will use the number. 4393 * 4394 * @param locale the locale to use, not null 4395 * @param chrono the chronology to use, not null 4396 * @return the formatter, not null 4397 * @throws IllegalArgumentException if the formatter cannot be found 4398 */ 4399 private DateTimeFormatter formatter(Locale locale, Chronology chrono) { 4400 String key = chrono.getId() + '|' + locale.toString() + '|' + dateStyle + timeStyle; 4401 DateTimeFormatter formatter = FORMATTER_CACHE.get(key); 4402 if (formatter == null) { 4403 String pattern = getLocalizedDateTimePattern(dateStyle, timeStyle, chrono, locale); 4404 formatter = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(locale); 4405 DateTimeFormatter old = FORMATTER_CACHE.putIfAbsent(key, formatter); 4406 if (old != null) { 4407 formatter = old; 4408 } 4409 } 4410 return formatter; 4411 } 4412 4413 @Override 4414 public String toString() { 4415 return "Localized(" + (dateStyle != null ? dateStyle : "") + "," + 4416 (timeStyle != null ? timeStyle : "") + ")"; 4417 } 4418 } 4419 4420 //----------------------------------------------------------------------- 4421 /** 4422 * Prints or parses a localized pattern from a localized field. 4423 * The specific formatter and parameters is not selected until the 4424 * the field is to be printed or parsed. 4425 * The locale is needed to select the proper WeekFields from which 4426 * the field for day-of-week, week-of-month, or week-of-year is selected. 4427 */ 4428 static final class WeekBasedFieldPrinterParser implements DateTimePrinterParser { 4429 private char chr; 4430 private int count; 4431 4432 /** 4433 * Constructor. 4434 * 4435 * @param chr the pattern format letter that added this PrinterParser. 4436 * @param count the repeat count of the format letter 4437 */ 4438 WeekBasedFieldPrinterParser(char chr, int count) { 4439 this.chr = chr; 4440 this.count = count; 4441 } 4442 4443 @Override 4444 public boolean format(DateTimePrintContext context, StringBuilder buf) { 4445 return printerParser(context.getLocale()).format(context, buf); 4446 } 4447 4448 @Override 4449 public int parse(DateTimeParseContext context, CharSequence text, int position) { 4450 return printerParser(context.getLocale()).parse(context, text, position); 4451 } 4452 4453 /** 4454 * Gets the printerParser to use based on the field and the locale. 4455 * 4456 * @param locale the locale to use, not null 4457 * @return the formatter, not null 4458 * @throws IllegalArgumentException if the formatter cannot be found 4459 */ 4460 private DateTimePrinterParser printerParser(Locale locale) { 4461 WeekFields weekDef = WeekFields.of(locale); 4462 TemporalField field = null; 4463 switch (chr) { 4464 case 'Y': 4465 field = weekDef.weekBasedYear(); 4466 if (count == 2) { 4467 return new ReducedPrinterParser(field, 2, 2, 0, ReducedPrinterParser.BASE_DATE, 0); 4468 } else { 4469 return new NumberPrinterParser(field, count, 19, 4470 (count < 4) ? SignStyle.NORMAL : SignStyle.EXCEEDS_PAD, -1); 4471 } 4472 case 'e': 4473 case 'c': 4474 field = weekDef.dayOfWeek(); 4475 break; 4476 case 'w': 4477 field = weekDef.weekOfWeekBasedYear(); 4478 break; 4479 case 'W': 4480 field = weekDef.weekOfMonth(); 4481 break; 4482 default: 4483 throw new IllegalStateException("unreachable"); 4484 } 4485 return new NumberPrinterParser(field, (count == 2 ? 2 : 1), 2, SignStyle.NOT_NEGATIVE); 4486 } 4487 4488 @Override 4489 public String toString() { 4490 StringBuilder sb = new StringBuilder(30); 4491 sb.append("Localized("); 4492 if (chr == 'Y') { 4493 if (count == 1) { 4494 sb.append("WeekBasedYear"); 4495 } else if (count == 2) { 4496 sb.append("ReducedValue(WeekBasedYear,2,2,2000-01-01)"); 4497 } else { 4498 sb.append("WeekBasedYear,").append(count).append(",") 4499 .append(19).append(",") 4500 .append((count < 4) ? SignStyle.NORMAL : SignStyle.EXCEEDS_PAD); 4501 } 4502 } else { 4503 switch (chr) { 4504 case 'c': 4505 case 'e': 4506 sb.append("DayOfWeek"); 4507 break; 4508 case 'w': 4509 sb.append("WeekOfWeekBasedYear"); 4510 break; 4511 case 'W': 4512 sb.append("WeekOfMonth"); 4513 break; 4514 default: 4515 break; 4516 } 4517 sb.append(","); 4518 sb.append(count); 4519 } 4520 sb.append(")"); 4521 return sb.toString(); 4522 } 4523 } 4524 4525 //------------------------------------------------------------------------- 4526 /** 4527 * Length comparator. 4528 */ 4529 static final Comparator<String> LENGTH_SORT = new Comparator<String>() { 4530 @Override 4531 public int compare(String str1, String str2) { 4532 return str1.length() == str2.length() ? str1.compareTo(str2) : str1.length() - str2.length(); 4533 } 4534 }; 4535 }