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