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