1 /* 2 * Copyright (c) 2012, 2016, 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.DAY_OF_WEEK; 66 import static java.time.temporal.ChronoField.DAY_OF_YEAR; 67 import static java.time.temporal.ChronoField.HOUR_OF_DAY; 68 import static java.time.temporal.ChronoField.MINUTE_OF_HOUR; 69 import static java.time.temporal.ChronoField.MONTH_OF_YEAR; 70 import static java.time.temporal.ChronoField.NANO_OF_SECOND; 71 import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; 72 import static java.time.temporal.ChronoField.YEAR; 73 74 import java.io.IOException; 75 import java.text.FieldPosition; 76 import java.text.Format; 77 import java.text.ParseException; 78 import java.text.ParsePosition; 79 import java.time.DateTimeException; 80 import java.time.Period; 81 import java.time.ZoneId; 82 import java.time.ZoneOffset; 83 import java.time.chrono.ChronoLocalDateTime; 84 import java.time.chrono.Chronology; 85 import java.time.chrono.IsoChronology; 86 import java.time.format.DateTimeFormatterBuilder.CompositePrinterParser; 87 import java.time.temporal.ChronoField; 88 import java.time.temporal.IsoFields; 89 import java.time.temporal.TemporalAccessor; 90 import java.time.temporal.TemporalField; 91 import java.time.temporal.TemporalQuery; 92 import java.util.Arrays; 93 import java.util.Collections; 94 import java.util.HashMap; 95 import java.util.HashSet; 96 import java.util.Locale; 97 import java.util.Map; 98 import java.util.Objects; 99 import java.util.Set; 100 101 /** 102 * Formatter for printing and parsing date-time objects. 103 * <p> 104 * This class provides the main application entry point for printing and parsing 105 * and provides common implementations of {@code DateTimeFormatter}: 106 * <ul> 107 * <li>Using predefined constants, such as {@link #ISO_LOCAL_DATE}</li> 108 * <li>Using pattern letters, such as {@code uuuu-MMM-dd}</li> 109 * <li>Using localized styles, such as {@code long} or {@code medium}</li> 110 * </ul> 111 * <p> 112 * More complex formatters are provided by 113 * {@link DateTimeFormatterBuilder DateTimeFormatterBuilder}. 114 * 115 * <p> 116 * The main date-time classes provide two methods - one for formatting, 117 * {@code format(DateTimeFormatter formatter)}, and one for parsing, 118 * {@code parse(CharSequence text, DateTimeFormatter formatter)}. 119 * <p>For example: 120 * <blockquote><pre> 121 * LocalDate date = LocalDate.now(); 122 * String text = date.format(formatter); 123 * LocalDate parsedDate = LocalDate.parse(text, formatter); 124 * </pre></blockquote> 125 * <p> 126 * In addition to the format, formatters can be created with desired Locale, 127 * Chronology, ZoneId, and DecimalStyle. 128 * <p> 129 * The {@link #withLocale withLocale} method returns a new formatter that 130 * overrides the locale. The locale affects some aspects of formatting and 131 * parsing. For example, the {@link #ofLocalizedDate ofLocalizedDate} provides a 132 * formatter that uses the locale specific date format. 133 * <p> 134 * The {@link #withChronology withChronology} method returns a new formatter 135 * that overrides the chronology. If overridden, the date-time value is 136 * converted to the chronology before formatting. During parsing the date-time 137 * value is converted to the chronology before it is returned. 138 * <p> 139 * The {@link #withZone withZone} method returns a new formatter that overrides 140 * the zone. If overridden, the date-time value is converted to a ZonedDateTime 141 * with the requested ZoneId before formatting. During parsing the ZoneId is 142 * applied before the value is returned. 143 * <p> 144 * The {@link #withDecimalStyle withDecimalStyle} method returns a new formatter that 145 * overrides the {@link DecimalStyle}. The DecimalStyle symbols are used for 146 * formatting and parsing. 147 * <p> 148 * Some applications may need to use the older {@link Format java.text.Format} 149 * class for formatting. The {@link #toFormat()} method returns an 150 * implementation of {@code java.text.Format}. 151 * 152 * <h3 id="predefined">Predefined Formatters</h3> 153 * <table summary="Predefined Formatters" cellpadding="2" cellspacing="3" border="0" > 154 * <thead> 155 * <tr class="tableSubHeadingColor"> 156 * <th class="colFirst" style="text-align:left">Formatter</th> 157 * <th class="colFirst" style="text-align:left">Description</th> 158 * <th class="colLast" style="text-align:left">Example</th> 159 * </tr> 160 * </thead> 161 * <tbody> 162 * <tr class="rowColor"> 163 * <td>{@link #ofLocalizedDate ofLocalizedDate(dateStyle)} </td> 164 * <td> Formatter with date style from the locale </td> 165 * <td> '2011-12-03'</td> 166 * </tr> 167 * <tr class="altColor"> 168 * <td> {@link #ofLocalizedTime ofLocalizedTime(timeStyle)} </td> 169 * <td> Formatter with time style from the locale </td> 170 * <td> '10:15:30'</td> 171 * </tr> 172 * <tr class="rowColor"> 173 * <td> {@link #ofLocalizedDateTime ofLocalizedDateTime(dateTimeStyle)} </td> 174 * <td> Formatter with a style for date and time from the locale</td> 175 * <td> '3 Jun 2008 11:05:30'</td> 176 * </tr> 177 * <tr class="altColor"> 178 * <td> {@link #ofLocalizedDateTime ofLocalizedDateTime(dateStyle,timeStyle)} 179 * </td> 180 * <td> Formatter with date and time styles from the locale </td> 181 * <td> '3 Jun 2008 11:05'</td> 182 * </tr> 183 * <tr class="rowColor"> 184 * <td> {@link #BASIC_ISO_DATE}</td> 185 * <td>Basic ISO date </td> <td>'20111203'</td> 186 * </tr> 187 * <tr class="altColor"> 188 * <td> {@link #ISO_LOCAL_DATE}</td> 189 * <td> ISO Local Date </td> 190 * <td>'2011-12-03'</td> 191 * </tr> 192 * <tr class="rowColor"> 193 * <td> {@link #ISO_OFFSET_DATE}</td> 194 * <td> ISO Date with offset </td> 195 * <td>'2011-12-03+01:00'</td> 196 * </tr> 197 * <tr class="altColor"> 198 * <td> {@link #ISO_DATE}</td> 199 * <td> ISO Date with or without offset </td> 200 * <td> '2011-12-03+01:00'; '2011-12-03'</td> 201 * </tr> 202 * <tr class="rowColor"> 203 * <td> {@link #ISO_LOCAL_TIME}</td> 204 * <td> Time without offset </td> 205 * <td>'10:15:30'</td> 206 * </tr> 207 * <tr class="altColor"> 208 * <td> {@link #ISO_OFFSET_TIME}</td> 209 * <td> Time with offset </td> 210 * <td>'10:15:30+01:00'</td> 211 * </tr> 212 * <tr class="rowColor"> 213 * <td> {@link #ISO_TIME}</td> 214 * <td> Time with or without offset </td> 215 * <td>'10:15:30+01:00'; '10:15:30'</td> 216 * </tr> 217 * <tr class="altColor"> 218 * <td> {@link #ISO_LOCAL_DATE_TIME}</td> 219 * <td> ISO Local Date and Time </td> 220 * <td>'2011-12-03T10:15:30'</td> 221 * </tr> 222 * <tr class="rowColor"> 223 * <td> {@link #ISO_OFFSET_DATE_TIME}</td> 224 * <td> Date Time with Offset 225 * </td><td>2011-12-03T10:15:30+01:00'</td> 226 * </tr> 227 * <tr class="altColor"> 228 * <td> {@link #ISO_ZONED_DATE_TIME}</td> 229 * <td> Zoned Date Time </td> 230 * <td>'2011-12-03T10:15:30+01:00[Europe/Paris]'</td> 231 * </tr> 232 * <tr class="rowColor"> 233 * <td> {@link #ISO_DATE_TIME}</td> 234 * <td> Date and time with ZoneId </td> 235 * <td>'2011-12-03T10:15:30+01:00[Europe/Paris]'</td> 236 * </tr> 237 * <tr class="altColor"> 238 * <td> {@link #ISO_ORDINAL_DATE}</td> 239 * <td> Year and day of year </td> 240 * <td>'2012-337'</td> 241 * </tr> 242 * <tr class="rowColor"> 243 * <td> {@link #ISO_WEEK_DATE}</td> 244 * <td> Year and Week </td> 245 * <td>2012-W48-6'</td></tr> 246 * <tr class="altColor"> 247 * <td> {@link #ISO_INSTANT}</td> 248 * <td> Date and Time of an Instant </td> 249 * <td>'2011-12-03T10:15:30Z' </td> 250 * </tr> 251 * <tr class="rowColor"> 252 * <td> {@link #RFC_1123_DATE_TIME}</td> 253 * <td> RFC 1123 / RFC 822 </td> 254 * <td>'Tue, 3 Jun 2008 11:05:30 GMT'</td> 255 * </tr> 256 * </tbody> 257 * </table> 258 * 259 * <h3 id="patterns">Patterns for Formatting and Parsing</h3> 260 * Patterns are based on a simple sequence of letters and symbols. 261 * A pattern is used to create a Formatter using the 262 * {@link #ofPattern(String)} and {@link #ofPattern(String, Locale)} methods. 263 * For example, 264 * {@code "d MMM uuuu"} will format 2011-12-03 as '3 Dec 2011'. 265 * A formatter created from a pattern can be used as many times as necessary, 266 * it is immutable and is thread-safe. 267 * <p> 268 * For example: 269 * <blockquote><pre> 270 * LocalDate date = LocalDate.now(); 271 * DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd"); 272 * String text = date.format(formatter); 273 * LocalDate parsedDate = LocalDate.parse(text, formatter); 274 * </pre></blockquote> 275 * <p> 276 * All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The 277 * following pattern letters are defined: 278 * <pre> 279 * Symbol Meaning Presentation Examples 280 * ------ ------- ------------ ------- 281 * G era text AD; Anno Domini; A 282 * u year year 2004; 04 283 * y year-of-era year 2004; 04 284 * D day-of-year number 189 285 * M/L month-of-year number/text 7; 07; Jul; July; J 286 * d day-of-month number 10 287 * g modified-julian-day number 2451334 288 * 289 * Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter 290 * Y week-based-year year 1996; 96 291 * w week-of-week-based-year number 27 292 * W week-of-month number 4 293 * E day-of-week text Tue; Tuesday; T 294 * e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T 295 * F day-of-week-in-month number 3 296 * 297 * a am-pm-of-day text PM 298 * h clock-hour-of-am-pm (1-12) number 12 299 * K hour-of-am-pm (0-11) number 0 300 * k clock-hour-of-day (1-24) number 24 301 * 302 * H hour-of-day (0-23) number 0 303 * m minute-of-hour number 30 304 * s second-of-minute number 55 305 * S fraction-of-second fraction 978 306 * A milli-of-day number 1234 307 * n nano-of-second number 987654321 308 * N nano-of-day number 1234000000 309 * 310 * V time-zone ID zone-id America/Los_Angeles; Z; -08:30 311 * v generic time-zone name zone-name Pacific Time; PT 312 * z time-zone name zone-name Pacific Standard Time; PST 313 * O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00 314 * X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15 315 * x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15 316 * Z zone-offset offset-Z +0000; -0800; -08:00 317 * 318 * p pad next pad modifier 1 319 * 320 * ' escape for text delimiter 321 * '' single quote literal ' 322 * [ optional section start 323 * ] optional section end 324 * # reserved for future use 325 * { reserved for future use 326 * } reserved for future use 327 * </pre> 328 * <p> 329 * The count of pattern letters determines the format. 330 * <p> 331 * <b>Text</b>: The text style is determined based on the number of pattern 332 * letters used. Less than 4 pattern letters will use the 333 * {@link TextStyle#SHORT short form}. Exactly 4 pattern letters will use the 334 * {@link TextStyle#FULL full form}. Exactly 5 pattern letters will use the 335 * {@link TextStyle#NARROW narrow form}. 336 * Pattern letters 'L', 'c', and 'q' specify the stand-alone form of the text styles. 337 * <p> 338 * <b>Number</b>: If the count of letters is one, then the value is output using 339 * the minimum number of digits and without padding. Otherwise, the count of digits 340 * is used as the width of the output field, with the value zero-padded as necessary. 341 * The following pattern letters have constraints on the count of letters. 342 * Only one letter of 'c' and 'F' can be specified. 343 * Up to two letters of 'd', 'H', 'h', 'K', 'k', 'm', and 's' can be specified. 344 * Up to three letters of 'D' can be specified. 345 * <p> 346 * <b>Number/Text</b>: If the count of pattern letters is 3 or greater, use the 347 * Text rules above. Otherwise use the Number rules above. 348 * <p> 349 * <b>Fraction</b>: Outputs the nano-of-second field as a fraction-of-second. 350 * The nano-of-second value has nine digits, thus the count of pattern letters 351 * is from 1 to 9. If it is less than 9, then the nano-of-second value is 352 * truncated, with only the most significant digits being output. 353 * <p> 354 * <b>Year</b>: The count of letters determines the minimum field width below 355 * which padding is used. If the count of letters is two, then a 356 * {@link DateTimeFormatterBuilder#appendValueReduced reduced} two digit form is 357 * used. For printing, this outputs the rightmost two digits. For parsing, this 358 * will parse using the base value of 2000, resulting in a year within the range 359 * 2000 to 2099 inclusive. If the count of letters is less than four (but not 360 * two), then the sign is only output for negative years as per 361 * {@link SignStyle#NORMAL}. Otherwise, the sign is output if the pad width is 362 * exceeded, as per {@link SignStyle#EXCEEDS_PAD}. 363 * <p> 364 * <b>ZoneId</b>: This outputs the time-zone ID, such as 'Europe/Paris'. If the 365 * count of letters is two, then the time-zone ID is output. Any other count of 366 * letters throws {@code IllegalArgumentException}. 367 * <p> 368 * <b>Zone names</b>: This outputs the display name of the time-zone ID. If the 369 * pattern letter is 'z' the output is the daylight savings aware zone name. 370 * If there is insufficient information to determine whether DST applies, 371 * the name ignoring daylight savings time will be used. 372 * If the count of letters is one, two or three, then the short name is output. 373 * If the count of letters is four, then the full name is output. 374 * Five or more letters throws {@code IllegalArgumentException}. 375 * <p> 376 * If the pattern letter is 'v' the output provides the zone name ignoring 377 * daylight savings time. If the count of letters is one, then the short name is output. 378 * If the count of letters is four, then the full name is output. 379 * Two, three and five or more letters throw {@code IllegalArgumentException}. 380 * <p> 381 * <b>Offset X and x</b>: This formats the offset based on the number of pattern 382 * letters. One letter outputs just the hour, such as '+01', unless the minute 383 * is non-zero in which case the minute is also output, such as '+0130'. Two 384 * letters outputs the hour and minute, without a colon, such as '+0130'. Three 385 * letters outputs the hour and minute, with a colon, such as '+01:30'. Four 386 * letters outputs the hour and minute and optional second, without a colon, 387 * such as '+013015'. Five letters outputs the hour and minute and optional 388 * second, with a colon, such as '+01:30:15'. Six or more letters throws 389 * {@code IllegalArgumentException}. Pattern letter 'X' (upper case) will output 390 * 'Z' when the offset to be output would be zero, whereas pattern letter 'x' 391 * (lower case) will output '+00', '+0000', or '+00:00'. 392 * <p> 393 * <b>Offset O</b>: This formats the localized offset based on the number of 394 * pattern letters. One letter outputs the {@linkplain TextStyle#SHORT short} 395 * form of the localized offset, which is localized offset text, such as 'GMT', 396 * with hour without leading zero, optional 2-digit minute and second if 397 * non-zero, and colon, for example 'GMT+8'. Four letters outputs the 398 * {@linkplain TextStyle#FULL full} form, which is localized offset text, 399 * such as 'GMT, with 2-digit hour and minute field, optional second field 400 * if non-zero, and colon, for example 'GMT+08:00'. Any other count of letters 401 * throws {@code IllegalArgumentException}. 402 * <p> 403 * <b>Offset Z</b>: This formats the offset based on the number of pattern 404 * letters. One, two or three letters outputs the hour and minute, without a 405 * colon, such as '+0130'. The output will be '+0000' when the offset is zero. 406 * Four letters outputs the {@linkplain TextStyle#FULL full} form of localized 407 * offset, equivalent to four letters of Offset-O. The output will be the 408 * corresponding localized offset text if the offset is zero. Five 409 * letters outputs the hour, minute, with optional second if non-zero, with 410 * colon. It outputs 'Z' if the offset is zero. 411 * Six or more letters throws {@code IllegalArgumentException}. 412 * <p> 413 * <b>Optional section</b>: The optional section markers work exactly like 414 * calling {@link DateTimeFormatterBuilder#optionalStart()} and 415 * {@link DateTimeFormatterBuilder#optionalEnd()}. 416 * <p> 417 * <b>Pad modifier</b>: Modifies the pattern that immediately follows to be 418 * padded with spaces. The pad width is determined by the number of pattern 419 * letters. This is the same as calling 420 * {@link DateTimeFormatterBuilder#padNext(int)}. 421 * <p> 422 * For example, 'ppH' outputs the hour-of-day padded on the left with spaces to 423 * a width of 2. 424 * <p> 425 * Any unrecognized letter is an error. Any non-letter character, other than 426 * '[', ']', '{', '}', '#' and the single quote will be output directly. 427 * Despite this, it is recommended to use single quotes around all characters 428 * that you want to output directly to ensure that future changes do not break 429 * your application. 430 * 431 * <h3 id="resolving">Resolving</h3> 432 * Parsing is implemented as a two-phase operation. 433 * First, the text is parsed using the layout defined by the formatter, producing 434 * a {@code Map} of field to value, a {@code ZoneId} and a {@code Chronology}. 435 * Second, the parsed data is <em>resolved</em>, by validating, combining and 436 * simplifying the various fields into more useful ones. 437 * <p> 438 * Five parsing methods are supplied by this class. 439 * Four of these perform both the parse and resolve phases. 440 * The fifth method, {@link #parseUnresolved(CharSequence, ParsePosition)}, 441 * only performs the first phase, leaving the result unresolved. 442 * As such, it is essentially a low-level operation. 443 * <p> 444 * The resolve phase is controlled by two parameters, set on this class. 445 * <p> 446 * The {@link ResolverStyle} is an enum that offers three different approaches, 447 * strict, smart and lenient. The smart option is the default. 448 * It can be set using {@link #withResolverStyle(ResolverStyle)}. 449 * <p> 450 * The {@link #withResolverFields(TemporalField...)} parameter allows the 451 * set of fields that will be resolved to be filtered before resolving starts. 452 * For example, if the formatter has parsed a year, month, day-of-month 453 * and day-of-year, then there are two approaches to resolve a date: 454 * (year + month + day-of-month) and (year + day-of-year). 455 * The resolver fields allows one of the two approaches to be selected. 456 * If no resolver fields are set then both approaches must result in the same date. 457 * <p> 458 * Resolving separate fields to form a complete date and time is a complex 459 * process with behaviour distributed across a number of classes. 460 * It follows these steps: 461 * <ol> 462 * <li>The chronology is determined. 463 * The chronology of the result is either the chronology that was parsed, 464 * or if no chronology was parsed, it is the chronology set on this class, 465 * or if that is null, it is {@code IsoChronology}. 466 * <li>The {@code ChronoField} date fields are resolved. 467 * This is achieved using {@link Chronology#resolveDate(Map, ResolverStyle)}. 468 * Documentation about field resolution is located in the implementation 469 * of {@code Chronology}. 470 * <li>The {@code ChronoField} time fields are resolved. 471 * This is documented on {@link ChronoField} and is the same for all chronologies. 472 * <li>Any fields that are not {@code ChronoField} are processed. 473 * This is achieved using {@link TemporalField#resolve(Map, TemporalAccessor, ResolverStyle)}. 474 * Documentation about field resolution is located in the implementation 475 * of {@code TemporalField}. 476 * <li>The {@code ChronoField} date and time fields are re-resolved. 477 * This allows fields in step four to produce {@code ChronoField} values 478 * and have them be processed into dates and times. 479 * <li>A {@code LocalTime} is formed if there is at least an hour-of-day available. 480 * This involves providing default values for minute, second and fraction of second. 481 * <li>Any remaining unresolved fields are cross-checked against any 482 * date and/or time that was resolved. Thus, an earlier stage would resolve 483 * (year + month + day-of-month) to a date, and this stage would check that 484 * day-of-week was valid for the date. 485 * <li>If an {@linkplain #parsedExcessDays() excess number of days} 486 * was parsed then it is added to the date if a date is available. 487 * <li> If a second-based field is present, but {@code LocalTime} was not parsed, 488 * then the resolver ensures that milli, micro and nano second values are 489 * available to meet the contract of {@link ChronoField}. 490 * These will be set to zero if missing. 491 * <li>If both date and time were parsed and either an offset or zone is present, 492 * the field {@link ChronoField#INSTANT_SECONDS} is created. 493 * If an offset was parsed then the offset will be combined with the 494 * {@code LocalDateTime} to form the instant, with any zone ignored. 495 * If a {@code ZoneId} was parsed without an offset then the zone will be 496 * combined with the {@code LocalDateTime} to form the instant using the rules 497 * of {@link ChronoLocalDateTime#atZone(ZoneId)}. 498 * </ol> 499 * 500 * @implSpec 501 * This class is immutable and thread-safe. 502 * 503 * @since 1.8 504 */ 505 public final class DateTimeFormatter { 506 507 /** 508 * The printer and/or parser to use, not null. 509 */ 510 private final CompositePrinterParser printerParser; 511 /** 512 * The locale to use for formatting, not null. 513 */ 514 private final Locale locale; 515 /** 516 * The symbols to use for formatting, not null. 517 */ 518 private final DecimalStyle decimalStyle; 519 /** 520 * The resolver style to use, not null. 521 */ 522 private final ResolverStyle resolverStyle; 523 /** 524 * The fields to use in resolving, null for all fields. 525 */ 526 private final Set<TemporalField> resolverFields; 527 /** 528 * The chronology to use for formatting, null for no override. 529 */ 530 private final Chronology chrono; 531 /** 532 * The zone to use for formatting, null for no override. 533 */ 534 private final ZoneId zone; 535 536 //----------------------------------------------------------------------- 537 /** 538 * Creates a formatter using the specified pattern. 539 * <p> 540 * This method will create a formatter based on a simple 541 * <a href="#patterns">pattern of letters and symbols</a> 542 * as described in the class documentation. 543 * For example, {@code d MMM uuuu} will format 2011-12-03 as '3 Dec 2011'. 544 * <p> 545 * The formatter will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}. 546 * This can be changed using {@link DateTimeFormatter#withLocale(Locale)} on the returned formatter 547 * Alternatively use the {@link #ofPattern(String, Locale)} variant of this method. 548 * <p> 549 * The returned formatter has no override chronology or zone. 550 * It uses {@link ResolverStyle#SMART SMART} resolver style. 551 * 552 * @param pattern the pattern to use, not null 553 * @return the formatter based on the pattern, not null 554 * @throws IllegalArgumentException if the pattern is invalid 555 * @see DateTimeFormatterBuilder#appendPattern(String) 556 */ 557 public static DateTimeFormatter ofPattern(String pattern) { 558 return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(); 559 } 560 561 /** 562 * Creates a formatter using the specified pattern and locale. 563 * <p> 564 * This method will create a formatter based on a simple 565 * <a href="#patterns">pattern of letters and symbols</a> 566 * as described in the class documentation. 567 * For example, {@code d MMM uuuu} will format 2011-12-03 as '3 Dec 2011'. 568 * <p> 569 * The formatter will use the specified locale. 570 * This can be changed using {@link DateTimeFormatter#withLocale(Locale)} on the returned formatter 571 * <p> 572 * The returned formatter has no override chronology or zone. 573 * It uses {@link ResolverStyle#SMART SMART} resolver style. 574 * 575 * @param pattern the pattern to use, not null 576 * @param locale the locale to use, not null 577 * @return the formatter based on the pattern, not null 578 * @throws IllegalArgumentException if the pattern is invalid 579 * @see DateTimeFormatterBuilder#appendPattern(String) 580 */ 581 public static DateTimeFormatter ofPattern(String pattern, Locale locale) { 582 return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(locale); 583 } 584 585 //----------------------------------------------------------------------- 586 /** 587 * Returns a locale specific date format for the ISO chronology. 588 * <p> 589 * This returns a formatter that will format or parse a date. 590 * The exact format pattern used varies by locale. 591 * <p> 592 * The locale is determined from the formatter. The formatter returned directly by 593 * this method will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}. 594 * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)} 595 * on the result of this method. 596 * <p> 597 * Note that the localized pattern is looked up lazily. 598 * This {@code DateTimeFormatter} holds the style required and the locale, 599 * looking up the pattern required on demand. 600 * <p> 601 * The returned formatter has a chronology of ISO set to ensure dates in 602 * other calendar systems are correctly converted. 603 * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style. 604 * 605 * @param dateStyle the formatter style to obtain, not null 606 * @return the date formatter, not null 607 */ 608 public static DateTimeFormatter ofLocalizedDate(FormatStyle dateStyle) { 609 Objects.requireNonNull(dateStyle, "dateStyle"); 610 return new DateTimeFormatterBuilder().appendLocalized(dateStyle, null) 611 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE); 612 } 613 614 /** 615 * Returns a locale specific time format for the ISO chronology. 616 * <p> 617 * This returns a formatter that will format or parse a time. 618 * The exact format pattern used varies by locale. 619 * <p> 620 * The locale is determined from the formatter. The formatter returned directly by 621 * this method will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}. 622 * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)} 623 * on the result of this method. 624 * <p> 625 * Note that the localized pattern is looked up lazily. 626 * This {@code DateTimeFormatter} holds the style required and the locale, 627 * looking up the pattern required on demand. 628 * <p> 629 * The returned formatter has a chronology of ISO set to ensure dates in 630 * other calendar systems are correctly converted. 631 * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style. 632 * The {@code FULL} and {@code LONG} styles typically require a time-zone. 633 * When formatting using these styles, a {@code ZoneId} must be available, 634 * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}. 635 * 636 * @param timeStyle the formatter style to obtain, not null 637 * @return the time formatter, not null 638 */ 639 public static DateTimeFormatter ofLocalizedTime(FormatStyle timeStyle) { 640 Objects.requireNonNull(timeStyle, "timeStyle"); 641 return new DateTimeFormatterBuilder().appendLocalized(null, timeStyle) 642 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE); 643 } 644 645 /** 646 * Returns a locale specific date-time formatter for the ISO chronology. 647 * <p> 648 * This returns a formatter that will format or parse a date-time. 649 * The exact format pattern used varies by locale. 650 * <p> 651 * The locale is determined from the formatter. The formatter returned directly by 652 * this method will use the {@link Locale#getDefault(Locale.Category) default FORMAT locale}. 653 * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)} 654 * on the result of this method. 655 * <p> 656 * Note that the localized pattern is looked up lazily. 657 * This {@code DateTimeFormatter} holds the style required and the locale, 658 * looking up the pattern required on demand. 659 * <p> 660 * The returned formatter has a chronology of ISO set to ensure dates in 661 * other calendar systems are correctly converted. 662 * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style. 663 * The {@code FULL} and {@code LONG} styles typically require a time-zone. 664 * When formatting using these styles, a {@code ZoneId} must be available, 665 * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}. 666 * 667 * @param dateTimeStyle the formatter style to obtain, not null 668 * @return the date-time formatter, not null 669 */ 670 public static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateTimeStyle) { 671 Objects.requireNonNull(dateTimeStyle, "dateTimeStyle"); 672 return new DateTimeFormatterBuilder().appendLocalized(dateTimeStyle, dateTimeStyle) 673 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE); 674 } 675 676 /** 677 * Returns a locale specific date and time format for the ISO chronology. 678 * <p> 679 * This returns a formatter that will format or parse a date-time. 680 * The exact format pattern used varies by locale. 681 * <p> 682 * The locale is determined from the formatter. The formatter returned directly by 683 * this method will use the {@link Locale#getDefault() default FORMAT locale}. 684 * The locale can be controlled using {@link DateTimeFormatter#withLocale(Locale) withLocale(Locale)} 685 * on the result of this method. 686 * <p> 687 * Note that the localized pattern is looked up lazily. 688 * This {@code DateTimeFormatter} holds the style required and the locale, 689 * looking up the pattern required on demand. 690 * <p> 691 * The returned formatter has a chronology of ISO set to ensure dates in 692 * other calendar systems are correctly converted. 693 * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style. 694 * The {@code FULL} and {@code LONG} styles typically require a time-zone. 695 * When formatting using these styles, a {@code ZoneId} must be available, 696 * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}. 697 * 698 * @param dateStyle the date formatter style to obtain, not null 699 * @param timeStyle the time formatter style to obtain, not null 700 * @return the date, time or date-time formatter, not null 701 */ 702 public static DateTimeFormatter ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle) { 703 Objects.requireNonNull(dateStyle, "dateStyle"); 704 Objects.requireNonNull(timeStyle, "timeStyle"); 705 return new DateTimeFormatterBuilder().appendLocalized(dateStyle, timeStyle) 706 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE); 707 } 708 709 //----------------------------------------------------------------------- 710 /** 711 * The ISO date formatter that formats or parses a date without an 712 * offset, such as '2011-12-03'. 713 * <p> 714 * This returns an immutable formatter capable of formatting and parsing 715 * the ISO-8601 extended local date format. 716 * The format consists of: 717 * <ul> 718 * <li>Four digits or more for the {@link ChronoField#YEAR year}. 719 * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits. 720 * Years outside that range will have a prefixed positive or negative symbol. 721 * <li>A dash 722 * <li>Two digits for the {@link ChronoField#MONTH_OF_YEAR month-of-year}. 723 * This is pre-padded by zero to ensure two digits. 724 * <li>A dash 725 * <li>Two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}. 726 * This is pre-padded by zero to ensure two digits. 727 * </ul> 728 * <p> 729 * The returned formatter has a chronology of ISO set to ensure dates in 730 * other calendar systems are correctly converted. 731 * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style. 732 */ 733 public static final DateTimeFormatter ISO_LOCAL_DATE; 734 static { 735 ISO_LOCAL_DATE = new DateTimeFormatterBuilder() 736 .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD) 737 .appendLiteral('-') 738 .appendValue(MONTH_OF_YEAR, 2) 739 .appendLiteral('-') 740 .appendValue(DAY_OF_MONTH, 2) 741 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE); 742 } 743 744 //----------------------------------------------------------------------- 745 /** 746 * The ISO date formatter that formats or parses a date with an 747 * offset, such as '2011-12-03+01:00'. 748 * <p> 749 * This returns an immutable formatter capable of formatting and parsing 750 * the ISO-8601 extended offset date format. 751 * The format consists of: 752 * <ul> 753 * <li>The {@link #ISO_LOCAL_DATE} 754 * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then 755 * they will be handled even though this is not part of the ISO-8601 standard. 756 * Parsing is case insensitive. 757 * </ul> 758 * <p> 759 * The returned formatter has a chronology of ISO set to ensure dates in 760 * other calendar systems are correctly converted. 761 * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style. 762 */ 763 public static final DateTimeFormatter ISO_OFFSET_DATE; 764 static { 765 ISO_OFFSET_DATE = new DateTimeFormatterBuilder() 766 .parseCaseInsensitive() 767 .append(ISO_LOCAL_DATE) 768 .appendOffsetId() 769 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE); 770 } 771 772 //----------------------------------------------------------------------- 773 /** 774 * The ISO date formatter that formats or parses a date with the 775 * offset if available, such as '2011-12-03' or '2011-12-03+01:00'. 776 * <p> 777 * This returns an immutable formatter capable of formatting and parsing 778 * the ISO-8601 extended date format. 779 * The format consists of: 780 * <ul> 781 * <li>The {@link #ISO_LOCAL_DATE} 782 * <li>If the offset is not available then the format is complete. 783 * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then 784 * they will be handled even though this is not part of the ISO-8601 standard. 785 * Parsing is case insensitive. 786 * </ul> 787 * <p> 788 * As this formatter has an optional element, it may be necessary to parse using 789 * {@link DateTimeFormatter#parseBest}. 790 * <p> 791 * The returned formatter has a chronology of ISO set to ensure dates in 792 * other calendar systems are correctly converted. 793 * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style. 794 */ 795 public static final DateTimeFormatter ISO_DATE; 796 static { 797 ISO_DATE = new DateTimeFormatterBuilder() 798 .parseCaseInsensitive() 799 .append(ISO_LOCAL_DATE) 800 .optionalStart() 801 .appendOffsetId() 802 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE); 803 } 804 805 //----------------------------------------------------------------------- 806 /** 807 * The ISO time formatter that formats or parses a time without an 808 * offset, such as '10:15' or '10:15:30'. 809 * <p> 810 * This returns an immutable formatter capable of formatting and parsing 811 * the ISO-8601 extended local time format. 812 * The format consists of: 813 * <ul> 814 * <li>Two digits for the {@link ChronoField#HOUR_OF_DAY hour-of-day}. 815 * This is pre-padded by zero to ensure two digits. 816 * <li>A colon 817 * <li>Two digits for the {@link ChronoField#MINUTE_OF_HOUR minute-of-hour}. 818 * This is pre-padded by zero to ensure two digits. 819 * <li>If the second-of-minute is not available then the format is complete. 820 * <li>A colon 821 * <li>Two digits for the {@link ChronoField#SECOND_OF_MINUTE second-of-minute}. 822 * This is pre-padded by zero to ensure two digits. 823 * <li>If the nano-of-second is zero or not available then the format is complete. 824 * <li>A decimal point 825 * <li>One to nine digits for the {@link ChronoField#NANO_OF_SECOND nano-of-second}. 826 * As many digits will be output as required. 827 * </ul> 828 * <p> 829 * The returned formatter has no override chronology or zone. 830 * It uses the {@link ResolverStyle#STRICT STRICT} resolver style. 831 */ 832 public static final DateTimeFormatter ISO_LOCAL_TIME; 833 static { 834 ISO_LOCAL_TIME = new DateTimeFormatterBuilder() 835 .appendValue(HOUR_OF_DAY, 2) 836 .appendLiteral(':') 837 .appendValue(MINUTE_OF_HOUR, 2) 838 .optionalStart() 839 .appendLiteral(':') 840 .appendValue(SECOND_OF_MINUTE, 2) 841 .optionalStart() 842 .appendFraction(NANO_OF_SECOND, 0, 9, true) 843 .toFormatter(ResolverStyle.STRICT, null); 844 } 845 846 //----------------------------------------------------------------------- 847 /** 848 * The ISO time formatter that formats or parses a time with an 849 * offset, such as '10:15+01:00' or '10:15:30+01:00'. 850 * <p> 851 * This returns an immutable formatter capable of formatting and parsing 852 * the ISO-8601 extended offset time format. 853 * The format consists of: 854 * <ul> 855 * <li>The {@link #ISO_LOCAL_TIME} 856 * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then 857 * they will be handled even though this is not part of the ISO-8601 standard. 858 * Parsing is case insensitive. 859 * </ul> 860 * <p> 861 * The returned formatter has no override chronology or zone. 862 * It uses the {@link ResolverStyle#STRICT STRICT} resolver style. 863 */ 864 public static final DateTimeFormatter ISO_OFFSET_TIME; 865 static { 866 ISO_OFFSET_TIME = new DateTimeFormatterBuilder() 867 .parseCaseInsensitive() 868 .append(ISO_LOCAL_TIME) 869 .appendOffsetId() 870 .toFormatter(ResolverStyle.STRICT, null); 871 } 872 873 //----------------------------------------------------------------------- 874 /** 875 * The ISO time formatter that formats or parses a time, with the 876 * offset if available, such as '10:15', '10:15:30' or '10:15:30+01:00'. 877 * <p> 878 * This returns an immutable formatter capable of formatting and parsing 879 * the ISO-8601 extended offset time format. 880 * The format consists of: 881 * <ul> 882 * <li>The {@link #ISO_LOCAL_TIME} 883 * <li>If the offset is not available then the format is complete. 884 * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then 885 * they will be handled even though this is not part of the ISO-8601 standard. 886 * Parsing is case insensitive. 887 * </ul> 888 * <p> 889 * As this formatter has an optional element, it may be necessary to parse using 890 * {@link DateTimeFormatter#parseBest}. 891 * <p> 892 * The returned formatter has no override chronology or zone. 893 * It uses the {@link ResolverStyle#STRICT STRICT} resolver style. 894 */ 895 public static final DateTimeFormatter ISO_TIME; 896 static { 897 ISO_TIME = new DateTimeFormatterBuilder() 898 .parseCaseInsensitive() 899 .append(ISO_LOCAL_TIME) 900 .optionalStart() 901 .appendOffsetId() 902 .toFormatter(ResolverStyle.STRICT, null); 903 } 904 905 //----------------------------------------------------------------------- 906 /** 907 * The ISO date-time formatter that formats or parses a date-time without 908 * an offset, such as '2011-12-03T10:15:30'. 909 * <p> 910 * This returns an immutable formatter capable of formatting and parsing 911 * the ISO-8601 extended offset date-time format. 912 * The format consists of: 913 * <ul> 914 * <li>The {@link #ISO_LOCAL_DATE} 915 * <li>The letter 'T'. Parsing is case insensitive. 916 * <li>The {@link #ISO_LOCAL_TIME} 917 * </ul> 918 * <p> 919 * The returned formatter has a chronology of ISO set to ensure dates in 920 * other calendar systems are correctly converted. 921 * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style. 922 */ 923 public static final DateTimeFormatter ISO_LOCAL_DATE_TIME; 924 static { 925 ISO_LOCAL_DATE_TIME = new DateTimeFormatterBuilder() 926 .parseCaseInsensitive() 927 .append(ISO_LOCAL_DATE) 928 .appendLiteral('T') 929 .append(ISO_LOCAL_TIME) 930 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE); 931 } 932 933 //----------------------------------------------------------------------- 934 /** 935 * The ISO date-time formatter that formats or parses a date-time with an 936 * offset, such as '2011-12-03T10:15:30+01:00'. 937 * <p> 938 * This returns an immutable formatter capable of formatting and parsing 939 * the ISO-8601 extended offset date-time format. 940 * The format consists of: 941 * <ul> 942 * <li>The {@link #ISO_LOCAL_DATE_TIME} 943 * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then 944 * they will be handled even though this is not part of the ISO-8601 standard. 945 * The offset parsing is lenient, which allows the minutes and seconds to be optional. 946 * Parsing is case insensitive. 947 * </ul> 948 * <p> 949 * The returned formatter has a chronology of ISO set to ensure dates in 950 * other calendar systems are correctly converted. 951 * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style. 952 */ 953 public static final DateTimeFormatter ISO_OFFSET_DATE_TIME; 954 static { 955 ISO_OFFSET_DATE_TIME = new DateTimeFormatterBuilder() 956 .parseCaseInsensitive() 957 .append(ISO_LOCAL_DATE_TIME) 958 .parseLenient() 959 .appendOffsetId() 960 .parseStrict() 961 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE); 962 } 963 964 //----------------------------------------------------------------------- 965 /** 966 * The ISO-like date-time formatter that formats or parses a date-time with 967 * offset and zone, such as '2011-12-03T10:15:30+01:00[Europe/Paris]'. 968 * <p> 969 * This returns an immutable formatter capable of formatting and parsing 970 * a format that extends the ISO-8601 extended offset date-time format 971 * to add the time-zone. 972 * The section in square brackets is not part of the ISO-8601 standard. 973 * The format consists of: 974 * <ul> 975 * <li>The {@link #ISO_OFFSET_DATE_TIME} 976 * <li>If the zone ID is not available or is a {@code ZoneOffset} then the format is complete. 977 * <li>An open square bracket '['. 978 * <li>The {@link ZoneId#getId() zone ID}. This is not part of the ISO-8601 standard. 979 * Parsing is case sensitive. 980 * <li>A close square bracket ']'. 981 * </ul> 982 * <p> 983 * The returned formatter has a chronology of ISO set to ensure dates in 984 * other calendar systems are correctly converted. 985 * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style. 986 */ 987 public static final DateTimeFormatter ISO_ZONED_DATE_TIME; 988 static { 989 ISO_ZONED_DATE_TIME = new DateTimeFormatterBuilder() 990 .append(ISO_OFFSET_DATE_TIME) 991 .optionalStart() 992 .appendLiteral('[') 993 .parseCaseSensitive() 994 .appendZoneRegionId() 995 .appendLiteral(']') 996 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE); 997 } 998 999 //----------------------------------------------------------------------- 1000 /** 1001 * The ISO-like date-time formatter that formats or parses a date-time with 1002 * the offset and zone if available, such as '2011-12-03T10:15:30', 1003 * '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'. 1004 * <p> 1005 * This returns an immutable formatter capable of formatting and parsing 1006 * the ISO-8601 extended local or offset date-time format, as well as the 1007 * extended non-ISO form specifying the time-zone. 1008 * The format consists of: 1009 * <ul> 1010 * <li>The {@link #ISO_LOCAL_DATE_TIME} 1011 * <li>If the offset is not available to format or parse then the format is complete. 1012 * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then 1013 * they will be handled even though this is not part of the ISO-8601 standard. 1014 * <li>If the zone ID is not available or is a {@code ZoneOffset} then the format is complete. 1015 * <li>An open square bracket '['. 1016 * <li>The {@link ZoneId#getId() zone ID}. This is not part of the ISO-8601 standard. 1017 * Parsing is case sensitive. 1018 * <li>A close square bracket ']'. 1019 * </ul> 1020 * <p> 1021 * As this formatter has an optional element, it may be necessary to parse using 1022 * {@link DateTimeFormatter#parseBest}. 1023 * <p> 1024 * The returned formatter has a chronology of ISO set to ensure dates in 1025 * other calendar systems are correctly converted. 1026 * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style. 1027 */ 1028 public static final DateTimeFormatter ISO_DATE_TIME; 1029 static { 1030 ISO_DATE_TIME = new DateTimeFormatterBuilder() 1031 .append(ISO_LOCAL_DATE_TIME) 1032 .optionalStart() 1033 .appendOffsetId() 1034 .optionalStart() 1035 .appendLiteral('[') 1036 .parseCaseSensitive() 1037 .appendZoneRegionId() 1038 .appendLiteral(']') 1039 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE); 1040 } 1041 1042 //----------------------------------------------------------------------- 1043 /** 1044 * The ISO date formatter that formats or parses the ordinal date 1045 * without an offset, such as '2012-337'. 1046 * <p> 1047 * This returns an immutable formatter capable of formatting and parsing 1048 * the ISO-8601 extended ordinal date format. 1049 * The format consists of: 1050 * <ul> 1051 * <li>Four digits or more for the {@link ChronoField#YEAR year}. 1052 * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits. 1053 * Years outside that range will have a prefixed positive or negative symbol. 1054 * <li>A dash 1055 * <li>Three digits for the {@link ChronoField#DAY_OF_YEAR day-of-year}. 1056 * This is pre-padded by zero to ensure three digits. 1057 * <li>If the offset is not available to format or parse then the format is complete. 1058 * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then 1059 * they will be handled even though this is not part of the ISO-8601 standard. 1060 * Parsing is case insensitive. 1061 * </ul> 1062 * <p> 1063 * As this formatter has an optional element, it may be necessary to parse using 1064 * {@link DateTimeFormatter#parseBest}. 1065 * <p> 1066 * The returned formatter has a chronology of ISO set to ensure dates in 1067 * other calendar systems are correctly converted. 1068 * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style. 1069 */ 1070 public static final DateTimeFormatter ISO_ORDINAL_DATE; 1071 static { 1072 ISO_ORDINAL_DATE = new DateTimeFormatterBuilder() 1073 .parseCaseInsensitive() 1074 .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD) 1075 .appendLiteral('-') 1076 .appendValue(DAY_OF_YEAR, 3) 1077 .optionalStart() 1078 .appendOffsetId() 1079 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE); 1080 } 1081 1082 //----------------------------------------------------------------------- 1083 /** 1084 * The ISO date formatter that formats or parses the week-based date 1085 * without an offset, such as '2012-W48-6'. 1086 * <p> 1087 * This returns an immutable formatter capable of formatting and parsing 1088 * the ISO-8601 extended week-based date format. 1089 * The format consists of: 1090 * <ul> 1091 * <li>Four digits or more for the {@link IsoFields#WEEK_BASED_YEAR week-based-year}. 1092 * Years in the range 0000 to 9999 will be pre-padded by zero to ensure four digits. 1093 * Years outside that range will have a prefixed positive or negative symbol. 1094 * <li>A dash 1095 * <li>The letter 'W'. Parsing is case insensitive. 1096 * <li>Two digits for the {@link IsoFields#WEEK_OF_WEEK_BASED_YEAR week-of-week-based-year}. 1097 * This is pre-padded by zero to ensure three digits. 1098 * <li>A dash 1099 * <li>One digit for the {@link ChronoField#DAY_OF_WEEK day-of-week}. 1100 * The value run from Monday (1) to Sunday (7). 1101 * <li>If the offset is not available to format or parse then the format is complete. 1102 * <li>The {@link ZoneOffset#getId() offset ID}. If the offset has seconds then 1103 * they will be handled even though this is not part of the ISO-8601 standard. 1104 * Parsing is case insensitive. 1105 * </ul> 1106 * <p> 1107 * As this formatter has an optional element, it may be necessary to parse using 1108 * {@link DateTimeFormatter#parseBest}. 1109 * <p> 1110 * The returned formatter has a chronology of ISO set to ensure dates in 1111 * other calendar systems are correctly converted. 1112 * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style. 1113 */ 1114 public static final DateTimeFormatter ISO_WEEK_DATE; 1115 static { 1116 ISO_WEEK_DATE = new DateTimeFormatterBuilder() 1117 .parseCaseInsensitive() 1118 .appendValue(IsoFields.WEEK_BASED_YEAR, 4, 10, SignStyle.EXCEEDS_PAD) 1119 .appendLiteral("-W") 1120 .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2) 1121 .appendLiteral('-') 1122 .appendValue(DAY_OF_WEEK, 1) 1123 .optionalStart() 1124 .appendOffsetId() 1125 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE); 1126 } 1127 1128 //----------------------------------------------------------------------- 1129 /** 1130 * The ISO instant formatter that formats or parses an instant in UTC, 1131 * such as '2011-12-03T10:15:30Z'. 1132 * <p> 1133 * This returns an immutable formatter capable of formatting and parsing 1134 * the ISO-8601 instant format. 1135 * When formatting, the second-of-minute is always output. 1136 * The nano-of-second outputs zero, three, six or nine digits as necessary. 1137 * When parsing, time to at least the seconds field is required. 1138 * Fractional seconds from zero to nine are parsed. 1139 * The localized decimal style is not used. 1140 * <p> 1141 * This is a special case formatter intended to allow a human readable form 1142 * of an {@link java.time.Instant}. The {@code Instant} class is designed to 1143 * only represent a point in time and internally stores a value in nanoseconds 1144 * from a fixed epoch of 1970-01-01Z. As such, an {@code Instant} cannot be 1145 * formatted as a date or time without providing some form of time-zone. 1146 * This formatter allows the {@code Instant} to be formatted, by providing 1147 * a suitable conversion using {@code ZoneOffset.UTC}. 1148 * <p> 1149 * The format consists of: 1150 * <ul> 1151 * <li>The {@link #ISO_OFFSET_DATE_TIME} where the instant is converted from 1152 * {@link ChronoField#INSTANT_SECONDS} and {@link ChronoField#NANO_OF_SECOND} 1153 * using the {@code UTC} offset. Parsing is case insensitive. 1154 * </ul> 1155 * <p> 1156 * The returned formatter has no override chronology or zone. 1157 * It uses the {@link ResolverStyle#STRICT STRICT} resolver style. 1158 */ 1159 public static final DateTimeFormatter ISO_INSTANT; 1160 static { 1161 ISO_INSTANT = new DateTimeFormatterBuilder() 1162 .parseCaseInsensitive() 1163 .appendInstant() 1164 .toFormatter(ResolverStyle.STRICT, null); 1165 } 1166 1167 //----------------------------------------------------------------------- 1168 /** 1169 * The ISO date formatter that formats or parses a date without an 1170 * offset, such as '20111203'. 1171 * <p> 1172 * This returns an immutable formatter capable of formatting and parsing 1173 * the ISO-8601 basic local date format. 1174 * The format consists of: 1175 * <ul> 1176 * <li>Four digits for the {@link ChronoField#YEAR year}. 1177 * Only years in the range 0000 to 9999 are supported. 1178 * <li>Two digits for the {@link ChronoField#MONTH_OF_YEAR month-of-year}. 1179 * This is pre-padded by zero to ensure two digits. 1180 * <li>Two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}. 1181 * This is pre-padded by zero to ensure two digits. 1182 * <li>If the offset is not available to format or parse then the format is complete. 1183 * <li>The {@link ZoneOffset#getId() offset ID} without colons. If the offset has 1184 * seconds then they will be handled even though this is not part of the ISO-8601 standard. 1185 * The offset parsing is lenient, which allows the minutes and seconds to be optional. 1186 * Parsing is case insensitive. 1187 * </ul> 1188 * <p> 1189 * As this formatter has an optional element, it may be necessary to parse using 1190 * {@link DateTimeFormatter#parseBest}. 1191 * <p> 1192 * The returned formatter has a chronology of ISO set to ensure dates in 1193 * other calendar systems are correctly converted. 1194 * It has no override zone and uses the {@link ResolverStyle#STRICT STRICT} resolver style. 1195 */ 1196 public static final DateTimeFormatter BASIC_ISO_DATE; 1197 static { 1198 BASIC_ISO_DATE = new DateTimeFormatterBuilder() 1199 .parseCaseInsensitive() 1200 .appendValue(YEAR, 4) 1201 .appendValue(MONTH_OF_YEAR, 2) 1202 .appendValue(DAY_OF_MONTH, 2) 1203 .optionalStart() 1204 .parseLenient() 1205 .appendOffset("+HHMMss", "Z") 1206 .parseStrict() 1207 .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE); 1208 } 1209 1210 //----------------------------------------------------------------------- 1211 /** 1212 * The RFC-1123 date-time formatter, such as 'Tue, 3 Jun 2008 11:05:30 GMT'. 1213 * <p> 1214 * This returns an immutable formatter capable of formatting and parsing 1215 * most of the RFC-1123 format. 1216 * RFC-1123 updates RFC-822 changing the year from two digits to four. 1217 * This implementation requires a four digit year. 1218 * This implementation also does not handle North American or military zone 1219 * names, only 'GMT' and offset amounts. 1220 * <p> 1221 * The format consists of: 1222 * <ul> 1223 * <li>If the day-of-week is not available to format or parse then jump to day-of-month. 1224 * <li>Three letter {@link ChronoField#DAY_OF_WEEK day-of-week} in English. 1225 * <li>A comma 1226 * <li>A space 1227 * <li>One or two digits for the {@link ChronoField#DAY_OF_MONTH day-of-month}. 1228 * <li>A space 1229 * <li>Three letter {@link ChronoField#MONTH_OF_YEAR month-of-year} in English. 1230 * <li>A space 1231 * <li>Four digits for the {@link ChronoField#YEAR year}. 1232 * Only years in the range 0000 to 9999 are supported. 1233 * <li>A space 1234 * <li>Two digits for the {@link ChronoField#HOUR_OF_DAY hour-of-day}. 1235 * This is pre-padded by zero to ensure two digits. 1236 * <li>A colon 1237 * <li>Two digits for the {@link ChronoField#MINUTE_OF_HOUR minute-of-hour}. 1238 * This is pre-padded by zero to ensure two digits. 1239 * <li>If the second-of-minute is not available then jump to the next space. 1240 * <li>A colon 1241 * <li>Two digits for the {@link ChronoField#SECOND_OF_MINUTE second-of-minute}. 1242 * This is pre-padded by zero to ensure two digits. 1243 * <li>A space 1244 * <li>The {@link ZoneOffset#getId() offset ID} without colons or seconds. 1245 * An offset of zero uses "GMT". North American zone names and military zone names are not handled. 1246 * </ul> 1247 * <p> 1248 * Parsing is case insensitive. 1249 * <p> 1250 * The returned formatter has a chronology of ISO set to ensure dates in 1251 * other calendar systems are correctly converted. 1252 * It has no override zone and uses the {@link ResolverStyle#SMART SMART} resolver style. 1253 */ 1254 public static final DateTimeFormatter RFC_1123_DATE_TIME; 1255 static { 1256 // manually code maps to ensure correct data always used 1257 // (locale data can be changed by application code) 1258 Map<Long, String> dow = new HashMap<>(); 1259 dow.put(1L, "Mon"); 1260 dow.put(2L, "Tue"); 1261 dow.put(3L, "Wed"); 1262 dow.put(4L, "Thu"); 1263 dow.put(5L, "Fri"); 1264 dow.put(6L, "Sat"); 1265 dow.put(7L, "Sun"); 1266 Map<Long, String> moy = new HashMap<>(); 1267 moy.put(1L, "Jan"); 1268 moy.put(2L, "Feb"); 1269 moy.put(3L, "Mar"); 1270 moy.put(4L, "Apr"); 1271 moy.put(5L, "May"); 1272 moy.put(6L, "Jun"); 1273 moy.put(7L, "Jul"); 1274 moy.put(8L, "Aug"); 1275 moy.put(9L, "Sep"); 1276 moy.put(10L, "Oct"); 1277 moy.put(11L, "Nov"); 1278 moy.put(12L, "Dec"); 1279 RFC_1123_DATE_TIME = new DateTimeFormatterBuilder() 1280 .parseCaseInsensitive() 1281 .parseLenient() 1282 .optionalStart() 1283 .appendText(DAY_OF_WEEK, dow) 1284 .appendLiteral(", ") 1285 .optionalEnd() 1286 .appendValue(DAY_OF_MONTH, 1, 2, SignStyle.NOT_NEGATIVE) 1287 .appendLiteral(' ') 1288 .appendText(MONTH_OF_YEAR, moy) 1289 .appendLiteral(' ') 1290 .appendValue(YEAR, 4) // 2 digit year not handled 1291 .appendLiteral(' ') 1292 .appendValue(HOUR_OF_DAY, 2) 1293 .appendLiteral(':') 1294 .appendValue(MINUTE_OF_HOUR, 2) 1295 .optionalStart() 1296 .appendLiteral(':') 1297 .appendValue(SECOND_OF_MINUTE, 2) 1298 .optionalEnd() 1299 .appendLiteral(' ') 1300 .appendOffset("+HHMM", "GMT") // should handle UT/Z/EST/EDT/CST/CDT/MST/MDT/PST/MDT 1301 .toFormatter(ResolverStyle.SMART, IsoChronology.INSTANCE); 1302 } 1303 1304 //----------------------------------------------------------------------- 1305 /** 1306 * A query that provides access to the excess days that were parsed. 1307 * <p> 1308 * This returns a singleton {@linkplain TemporalQuery query} that provides 1309 * access to additional information from the parse. The query always returns 1310 * a non-null period, with a zero period returned instead of null. 1311 * <p> 1312 * There are two situations where this query may return a non-zero period. 1313 * <ul> 1314 * <li>If the {@code ResolverStyle} is {@code LENIENT} and a time is parsed 1315 * without a date, then the complete result of the parse consists of a 1316 * {@code LocalTime} and an excess {@code Period} in days. 1317 * 1318 * <li>If the {@code ResolverStyle} is {@code SMART} and a time is parsed 1319 * without a date where the time is 24:00:00, then the complete result of 1320 * the parse consists of a {@code LocalTime} of 00:00:00 and an excess 1321 * {@code Period} of one day. 1322 * </ul> 1323 * <p> 1324 * In both cases, if a complete {@code ChronoLocalDateTime} or {@code Instant} 1325 * is parsed, then the excess days are added to the date part. 1326 * As a result, this query will return a zero period. 1327 * <p> 1328 * The {@code SMART} behaviour handles the common "end of day" 24:00 value. 1329 * Processing in {@code LENIENT} mode also produces the same result: 1330 * <pre> 1331 * Text to parse Parsed object Excess days 1332 * "2012-12-03T00:00" LocalDateTime.of(2012, 12, 3, 0, 0) ZERO 1333 * "2012-12-03T24:00" LocalDateTime.of(2012, 12, 4, 0, 0) ZERO 1334 * "00:00" LocalTime.of(0, 0) ZERO 1335 * "24:00" LocalTime.of(0, 0) Period.ofDays(1) 1336 * </pre> 1337 * The query can be used as follows: 1338 * <pre> 1339 * TemporalAccessor parsed = formatter.parse(str); 1340 * LocalTime time = parsed.query(LocalTime::from); 1341 * Period extraDays = parsed.query(DateTimeFormatter.parsedExcessDays()); 1342 * </pre> 1343 * @return a query that provides access to the excess days that were parsed 1344 */ 1345 public static final TemporalQuery<Period> parsedExcessDays() { 1346 return PARSED_EXCESS_DAYS; 1347 } 1348 private static final TemporalQuery<Period> PARSED_EXCESS_DAYS = t -> { 1349 if (t instanceof Parsed) { 1350 return ((Parsed) t).excessDays; 1351 } else { 1352 return Period.ZERO; 1353 } 1354 }; 1355 1356 /** 1357 * A query that provides access to whether a leap-second was parsed. 1358 * <p> 1359 * This returns a singleton {@linkplain TemporalQuery query} that provides 1360 * access to additional information from the parse. The query always returns 1361 * a non-null boolean, true if parsing saw a leap-second, false if not. 1362 * <p> 1363 * Instant parsing handles the special "leap second" time of '23:59:60'. 1364 * Leap seconds occur at '23:59:60' in the UTC time-zone, but at other 1365 * local times in different time-zones. To avoid this potential ambiguity, 1366 * the handling of leap-seconds is limited to 1367 * {@link DateTimeFormatterBuilder#appendInstant()}, as that method 1368 * always parses the instant with the UTC zone offset. 1369 * <p> 1370 * If the time '23:59:60' is received, then a simple conversion is applied, 1371 * replacing the second-of-minute of 60 with 59. This query can be used 1372 * on the parse result to determine if the leap-second adjustment was made. 1373 * The query will return {@code true} if it did adjust to remove the 1374 * leap-second, and {@code false} if not. Note that applying a leap-second 1375 * smoothing mechanism, such as UTC-SLS, is the responsibility of the 1376 * application, as follows: 1377 * <pre> 1378 * TemporalAccessor parsed = formatter.parse(str); 1379 * Instant instant = parsed.query(Instant::from); 1380 * if (parsed.query(DateTimeFormatter.parsedLeapSecond())) { 1381 * // validate leap-second is correct and apply correct smoothing 1382 * } 1383 * </pre> 1384 * @return a query that provides access to whether a leap-second was parsed 1385 */ 1386 public static final TemporalQuery<Boolean> parsedLeapSecond() { 1387 return PARSED_LEAP_SECOND; 1388 } 1389 private static final TemporalQuery<Boolean> PARSED_LEAP_SECOND = t -> { 1390 if (t instanceof Parsed) { 1391 return ((Parsed) t).leapSecond; 1392 } else { 1393 return Boolean.FALSE; 1394 } 1395 }; 1396 1397 //----------------------------------------------------------------------- 1398 /** 1399 * Constructor. 1400 * 1401 * @param printerParser the printer/parser to use, not null 1402 * @param locale the locale to use, not null 1403 * @param decimalStyle the DecimalStyle to use, not null 1404 * @param resolverStyle the resolver style to use, not null 1405 * @param resolverFields the fields to use during resolving, null for all fields 1406 * @param chrono the chronology to use, null for no override 1407 * @param zone the zone to use, null for no override 1408 */ 1409 DateTimeFormatter(CompositePrinterParser printerParser, 1410 Locale locale, DecimalStyle decimalStyle, 1411 ResolverStyle resolverStyle, Set<TemporalField> resolverFields, 1412 Chronology chrono, ZoneId zone) { 1413 this.printerParser = Objects.requireNonNull(printerParser, "printerParser"); 1414 this.resolverFields = resolverFields; 1415 this.locale = Objects.requireNonNull(locale, "locale"); 1416 this.decimalStyle = Objects.requireNonNull(decimalStyle, "decimalStyle"); 1417 this.resolverStyle = Objects.requireNonNull(resolverStyle, "resolverStyle"); 1418 this.chrono = chrono; 1419 this.zone = zone; 1420 } 1421 1422 //----------------------------------------------------------------------- 1423 /** 1424 * Gets the locale to be used during formatting. 1425 * <p> 1426 * This is used to lookup any part of the formatter needing specific 1427 * localization, such as the text or localized pattern. 1428 * 1429 * @return the locale of this formatter, not null 1430 */ 1431 public Locale getLocale() { 1432 return locale; 1433 } 1434 1435 /** 1436 * Returns a copy of this formatter with a new locale. 1437 * <p> 1438 * This is used to lookup any part of the formatter needing specific 1439 * localization, such as the text or localized pattern. 1440 * <p> 1441 * This instance is immutable and unaffected by this method call. 1442 * 1443 * @param locale the new locale, not null 1444 * @return a formatter based on this formatter with the requested locale, not null 1445 */ 1446 public DateTimeFormatter withLocale(Locale locale) { 1447 if (this.locale.equals(locale)) { 1448 return this; 1449 } 1450 return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone); 1451 } 1452 1453 //----------------------------------------------------------------------- 1454 /** 1455 * Gets the DecimalStyle to be used during formatting. 1456 * 1457 * @return the locale of this formatter, not null 1458 */ 1459 public DecimalStyle getDecimalStyle() { 1460 return decimalStyle; 1461 } 1462 1463 /** 1464 * Returns a copy of this formatter with a new DecimalStyle. 1465 * <p> 1466 * This instance is immutable and unaffected by this method call. 1467 * 1468 * @param decimalStyle the new DecimalStyle, not null 1469 * @return a formatter based on this formatter with the requested DecimalStyle, not null 1470 */ 1471 public DateTimeFormatter withDecimalStyle(DecimalStyle decimalStyle) { 1472 if (this.decimalStyle.equals(decimalStyle)) { 1473 return this; 1474 } 1475 return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone); 1476 } 1477 1478 //----------------------------------------------------------------------- 1479 /** 1480 * Gets the overriding chronology to be used during formatting. 1481 * <p> 1482 * This returns the override chronology, used to convert dates. 1483 * By default, a formatter has no override chronology, returning null. 1484 * See {@link #withChronology(Chronology)} for more details on overriding. 1485 * 1486 * @return the override chronology of this formatter, null if no override 1487 */ 1488 public Chronology getChronology() { 1489 return chrono; 1490 } 1491 1492 /** 1493 * Returns a copy of this formatter with a new override chronology. 1494 * <p> 1495 * This returns a formatter with similar state to this formatter but 1496 * with the override chronology set. 1497 * By default, a formatter has no override chronology, returning null. 1498 * <p> 1499 * If an override is added, then any date that is formatted or parsed will be affected. 1500 * <p> 1501 * When formatting, if the temporal object contains a date, then it will 1502 * be converted to a date in the override chronology. 1503 * Whether the temporal contains a date is determined by querying the 1504 * {@link ChronoField#EPOCH_DAY EPOCH_DAY} field. 1505 * Any time or zone will be retained unaltered unless overridden. 1506 * <p> 1507 * If the temporal object does not contain a date, but does contain one 1508 * or more {@code ChronoField} date fields, then a {@code DateTimeException} 1509 * is thrown. In all other cases, the override chronology is added to the temporal, 1510 * replacing any previous chronology, but without changing the date/time. 1511 * <p> 1512 * When parsing, there are two distinct cases to consider. 1513 * If a chronology has been parsed directly from the text, perhaps because 1514 * {@link DateTimeFormatterBuilder#appendChronologyId()} was used, then 1515 * this override chronology has no effect. 1516 * If no zone has been parsed, then this override chronology will be used 1517 * to interpret the {@code ChronoField} values into a date according to the 1518 * date resolving rules of the chronology. 1519 * <p> 1520 * This instance is immutable and unaffected by this method call. 1521 * 1522 * @param chrono the new chronology, null if no override 1523 * @return a formatter based on this formatter with the requested override chronology, not null 1524 */ 1525 public DateTimeFormatter withChronology(Chronology chrono) { 1526 if (Objects.equals(this.chrono, chrono)) { 1527 return this; 1528 } 1529 return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone); 1530 } 1531 1532 //----------------------------------------------------------------------- 1533 /** 1534 * Gets the overriding zone to be used during formatting. 1535 * <p> 1536 * This returns the override zone, used to convert instants. 1537 * By default, a formatter has no override zone, returning null. 1538 * See {@link #withZone(ZoneId)} for more details on overriding. 1539 * 1540 * @return the override zone of this formatter, null if no override 1541 */ 1542 public ZoneId getZone() { 1543 return zone; 1544 } 1545 1546 /** 1547 * Returns a copy of this formatter with a new override zone. 1548 * <p> 1549 * This returns a formatter with similar state to this formatter but 1550 * with the override zone set. 1551 * By default, a formatter has no override zone, returning null. 1552 * <p> 1553 * If an override is added, then any instant that is formatted or parsed will be affected. 1554 * <p> 1555 * When formatting, if the temporal object contains an instant, then it will 1556 * be converted to a zoned date-time using the override zone. 1557 * Whether the temporal is an instant is determined by querying the 1558 * {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} field. 1559 * If the input has a chronology then it will be retained unless overridden. 1560 * If the input does not have a chronology, such as {@code Instant}, then 1561 * the ISO chronology will be used. 1562 * <p> 1563 * If the temporal object does not contain an instant, but does contain 1564 * an offset then an additional check is made. If the normalized override 1565 * zone is an offset that differs from the offset of the temporal, then 1566 * a {@code DateTimeException} is thrown. In all other cases, the override 1567 * zone is added to the temporal, replacing any previous zone, but without 1568 * changing the date/time. 1569 * <p> 1570 * When parsing, there are two distinct cases to consider. 1571 * If a zone has been parsed directly from the text, perhaps because 1572 * {@link DateTimeFormatterBuilder#appendZoneId()} was used, then 1573 * this override zone has no effect. 1574 * If no zone has been parsed, then this override zone will be included in 1575 * the result of the parse where it can be used to build instants and date-times. 1576 * <p> 1577 * This instance is immutable and unaffected by this method call. 1578 * 1579 * @param zone the new override zone, null if no override 1580 * @return a formatter based on this formatter with the requested override zone, not null 1581 */ 1582 public DateTimeFormatter withZone(ZoneId zone) { 1583 if (Objects.equals(this.zone, zone)) { 1584 return this; 1585 } 1586 return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone); 1587 } 1588 1589 //----------------------------------------------------------------------- 1590 /** 1591 * Gets the resolver style to use during parsing. 1592 * <p> 1593 * This returns the resolver style, used during the second phase of parsing 1594 * when fields are resolved into dates and times. 1595 * By default, a formatter has the {@link ResolverStyle#SMART SMART} resolver style. 1596 * See {@link #withResolverStyle(ResolverStyle)} for more details. 1597 * 1598 * @return the resolver style of this formatter, not null 1599 */ 1600 public ResolverStyle getResolverStyle() { 1601 return resolverStyle; 1602 } 1603 1604 /** 1605 * Returns a copy of this formatter with a new resolver style. 1606 * <p> 1607 * This returns a formatter with similar state to this formatter but 1608 * with the resolver style set. By default, a formatter has the 1609 * {@link ResolverStyle#SMART SMART} resolver style. 1610 * <p> 1611 * Changing the resolver style only has an effect during parsing. 1612 * Parsing a text string occurs in two phases. 1613 * Phase 1 is a basic text parse according to the fields added to the builder. 1614 * Phase 2 resolves the parsed field-value pairs into date and/or time objects. 1615 * The resolver style is used to control how phase 2, resolving, happens. 1616 * See {@code ResolverStyle} for more information on the options available. 1617 * <p> 1618 * This instance is immutable and unaffected by this method call. 1619 * 1620 * @param resolverStyle the new resolver style, not null 1621 * @return a formatter based on this formatter with the requested resolver style, not null 1622 */ 1623 public DateTimeFormatter withResolverStyle(ResolverStyle resolverStyle) { 1624 Objects.requireNonNull(resolverStyle, "resolverStyle"); 1625 if (Objects.equals(this.resolverStyle, resolverStyle)) { 1626 return this; 1627 } 1628 return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone); 1629 } 1630 1631 //----------------------------------------------------------------------- 1632 /** 1633 * Gets the resolver fields to use during parsing. 1634 * <p> 1635 * This returns the resolver fields, used during the second phase of parsing 1636 * when fields are resolved into dates and times. 1637 * By default, a formatter has no resolver fields, and thus returns null. 1638 * See {@link #withResolverFields(Set)} for more details. 1639 * 1640 * @return the immutable set of resolver fields of this formatter, null if no fields 1641 */ 1642 public Set<TemporalField> getResolverFields() { 1643 return resolverFields; 1644 } 1645 1646 /** 1647 * Returns a copy of this formatter with a new set of resolver fields. 1648 * <p> 1649 * This returns a formatter with similar state to this formatter but with 1650 * the resolver fields set. By default, a formatter has no resolver fields. 1651 * <p> 1652 * Changing the resolver fields only has an effect during parsing. 1653 * Parsing a text string occurs in two phases. 1654 * Phase 1 is a basic text parse according to the fields added to the builder. 1655 * Phase 2 resolves the parsed field-value pairs into date and/or time objects. 1656 * The resolver fields are used to filter the field-value pairs between phase 1 and 2. 1657 * <p> 1658 * This can be used to select between two or more ways that a date or time might 1659 * be resolved. For example, if the formatter consists of year, month, day-of-month 1660 * and day-of-year, then there are two ways to resolve a date. 1661 * Calling this method with the arguments {@link ChronoField#YEAR YEAR} and 1662 * {@link ChronoField#DAY_OF_YEAR DAY_OF_YEAR} will ensure that the date is 1663 * resolved using the year and day-of-year, effectively meaning that the month 1664 * and day-of-month are ignored during the resolving phase. 1665 * <p> 1666 * In a similar manner, this method can be used to ignore secondary fields that 1667 * would otherwise be cross-checked. For example, if the formatter consists of year, 1668 * month, day-of-month and day-of-week, then there is only one way to resolve a 1669 * date, but the parsed value for day-of-week will be cross-checked against the 1670 * resolved date. Calling this method with the arguments {@link ChronoField#YEAR YEAR}, 1671 * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and 1672 * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} will ensure that the date is 1673 * resolved correctly, but without any cross-check for the day-of-week. 1674 * <p> 1675 * In implementation terms, this method behaves as follows. The result of the 1676 * parsing phase can be considered to be a map of field to value. The behavior 1677 * of this method is to cause that map to be filtered between phase 1 and 2, 1678 * removing all fields other than those specified as arguments to this method. 1679 * <p> 1680 * This instance is immutable and unaffected by this method call. 1681 * 1682 * @param resolverFields the new set of resolver fields, null if no fields 1683 * @return a formatter based on this formatter with the requested resolver style, not null 1684 */ 1685 public DateTimeFormatter withResolverFields(TemporalField... resolverFields) { 1686 Set<TemporalField> fields = null; 1687 if (resolverFields != null) { 1688 // Set.of cannot be used because it is hostile to nulls and duplicate elements 1689 fields = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(resolverFields))); 1690 } 1691 if (Objects.equals(this.resolverFields, fields)) { 1692 return this; 1693 } 1694 return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, fields, chrono, zone); 1695 } 1696 1697 /** 1698 * Returns a copy of this formatter with a new set of resolver fields. 1699 * <p> 1700 * This returns a formatter with similar state to this formatter but with 1701 * the resolver fields set. By default, a formatter has no resolver fields. 1702 * <p> 1703 * Changing the resolver fields only has an effect during parsing. 1704 * Parsing a text string occurs in two phases. 1705 * Phase 1 is a basic text parse according to the fields added to the builder. 1706 * Phase 2 resolves the parsed field-value pairs into date and/or time objects. 1707 * The resolver fields are used to filter the field-value pairs between phase 1 and 2. 1708 * <p> 1709 * This can be used to select between two or more ways that a date or time might 1710 * be resolved. For example, if the formatter consists of year, month, day-of-month 1711 * and day-of-year, then there are two ways to resolve a date. 1712 * Calling this method with the arguments {@link ChronoField#YEAR YEAR} and 1713 * {@link ChronoField#DAY_OF_YEAR DAY_OF_YEAR} will ensure that the date is 1714 * resolved using the year and day-of-year, effectively meaning that the month 1715 * and day-of-month are ignored during the resolving phase. 1716 * <p> 1717 * In a similar manner, this method can be used to ignore secondary fields that 1718 * would otherwise be cross-checked. For example, if the formatter consists of year, 1719 * month, day-of-month and day-of-week, then there is only one way to resolve a 1720 * date, but the parsed value for day-of-week will be cross-checked against the 1721 * resolved date. Calling this method with the arguments {@link ChronoField#YEAR YEAR}, 1722 * {@link ChronoField#MONTH_OF_YEAR MONTH_OF_YEAR} and 1723 * {@link ChronoField#DAY_OF_MONTH DAY_OF_MONTH} will ensure that the date is 1724 * resolved correctly, but without any cross-check for the day-of-week. 1725 * <p> 1726 * In implementation terms, this method behaves as follows. The result of the 1727 * parsing phase can be considered to be a map of field to value. The behavior 1728 * of this method is to cause that map to be filtered between phase 1 and 2, 1729 * removing all fields other than those specified as arguments to this method. 1730 * <p> 1731 * This instance is immutable and unaffected by this method call. 1732 * 1733 * @param resolverFields the new set of resolver fields, null if no fields 1734 * @return a formatter based on this formatter with the requested resolver style, not null 1735 */ 1736 public DateTimeFormatter withResolverFields(Set<TemporalField> resolverFields) { 1737 if (Objects.equals(this.resolverFields, resolverFields)) { 1738 return this; 1739 } 1740 if (resolverFields != null) { 1741 resolverFields = Collections.unmodifiableSet(new HashSet<>(resolverFields)); 1742 } 1743 return new DateTimeFormatter(printerParser, locale, decimalStyle, resolverStyle, resolverFields, chrono, zone); 1744 } 1745 1746 //----------------------------------------------------------------------- 1747 /** 1748 * Formats a date-time object using this formatter. 1749 * <p> 1750 * This formats the date-time to a String using the rules of the formatter. 1751 * 1752 * @param temporal the temporal object to format, not null 1753 * @return the formatted string, not null 1754 * @throws DateTimeException if an error occurs during formatting 1755 */ 1756 public String format(TemporalAccessor temporal) { 1757 StringBuilder buf = new StringBuilder(32); 1758 formatTo(temporal, buf); 1759 return buf.toString(); 1760 } 1761 1762 //----------------------------------------------------------------------- 1763 /** 1764 * Formats a date-time object to an {@code Appendable} using this formatter. 1765 * <p> 1766 * This outputs the formatted date-time to the specified destination. 1767 * {@link Appendable} is a general purpose interface that is implemented by all 1768 * key character output classes including {@code StringBuffer}, {@code StringBuilder}, 1769 * {@code PrintStream} and {@code Writer}. 1770 * <p> 1771 * Although {@code Appendable} methods throw an {@code IOException}, this method does not. 1772 * Instead, any {@code IOException} is wrapped in a runtime exception. 1773 * 1774 * @param temporal the temporal object to format, not null 1775 * @param appendable the appendable to format to, not null 1776 * @throws DateTimeException if an error occurs during formatting 1777 */ 1778 public void formatTo(TemporalAccessor temporal, Appendable appendable) { 1779 Objects.requireNonNull(temporal, "temporal"); 1780 Objects.requireNonNull(appendable, "appendable"); 1781 try { 1782 DateTimePrintContext context = new DateTimePrintContext(temporal, this); 1783 if (appendable instanceof StringBuilder) { 1784 printerParser.format(context, (StringBuilder) appendable); 1785 } else { 1786 // buffer output to avoid writing to appendable in case of error 1787 StringBuilder buf = new StringBuilder(32); 1788 printerParser.format(context, buf); 1789 appendable.append(buf); 1790 } 1791 } catch (IOException ex) { 1792 throw new DateTimeException(ex.getMessage(), ex); 1793 } 1794 } 1795 1796 //----------------------------------------------------------------------- 1797 /** 1798 * Fully parses the text producing a temporal object. 1799 * <p> 1800 * This parses the entire text producing a temporal object. 1801 * It is typically more useful to use {@link #parse(CharSequence, TemporalQuery)}. 1802 * The result of this method is {@code TemporalAccessor} which has been resolved, 1803 * applying basic validation checks to help ensure a valid date-time. 1804 * <p> 1805 * If the parse completes without reading the entire length of the text, 1806 * or a problem occurs during parsing or merging, then an exception is thrown. 1807 * 1808 * @param text the text to parse, not null 1809 * @return the parsed temporal object, not null 1810 * @throws DateTimeParseException if unable to parse the requested result 1811 */ 1812 public TemporalAccessor parse(CharSequence text) { 1813 Objects.requireNonNull(text, "text"); 1814 try { 1815 return parseResolved0(text, null); 1816 } catch (DateTimeParseException ex) { 1817 throw ex; 1818 } catch (RuntimeException ex) { 1819 throw createError(text, ex); 1820 } 1821 } 1822 1823 /** 1824 * Parses the text using this formatter, providing control over the text position. 1825 * <p> 1826 * This parses the text without requiring the parse to start from the beginning 1827 * of the string or finish at the end. 1828 * The result of this method is {@code TemporalAccessor} which has been resolved, 1829 * applying basic validation checks to help ensure a valid date-time. 1830 * <p> 1831 * The text will be parsed from the specified start {@code ParsePosition}. 1832 * The entire length of the text does not have to be parsed, the {@code ParsePosition} 1833 * will be updated with the index at the end of parsing. 1834 * <p> 1835 * The operation of this method is slightly different to similar methods using 1836 * {@code ParsePosition} on {@code java.text.Format}. That class will return 1837 * errors using the error index on the {@code ParsePosition}. By contrast, this 1838 * method will throw a {@link DateTimeParseException} if an error occurs, with 1839 * the exception containing the error index. 1840 * This change in behavior is necessary due to the increased complexity of 1841 * parsing and resolving dates/times in this API. 1842 * <p> 1843 * If the formatter parses the same field more than once with different values, 1844 * the result will be an error. 1845 * 1846 * @param text the text to parse, not null 1847 * @param position the position to parse from, updated with length parsed 1848 * and the index of any error, not null 1849 * @return the parsed temporal object, not null 1850 * @throws DateTimeParseException if unable to parse the requested result 1851 * @throws IndexOutOfBoundsException if the position is invalid 1852 */ 1853 public TemporalAccessor parse(CharSequence text, ParsePosition position) { 1854 Objects.requireNonNull(text, "text"); 1855 Objects.requireNonNull(position, "position"); 1856 try { 1857 return parseResolved0(text, position); 1858 } catch (DateTimeParseException | IndexOutOfBoundsException ex) { 1859 throw ex; 1860 } catch (RuntimeException ex) { 1861 throw createError(text, ex); 1862 } 1863 } 1864 1865 //----------------------------------------------------------------------- 1866 /** 1867 * Fully parses the text producing an object of the specified type. 1868 * <p> 1869 * Most applications should use this method for parsing. 1870 * It parses the entire text to produce the required date-time. 1871 * The query is typically a method reference to a {@code from(TemporalAccessor)} method. 1872 * For example: 1873 * <pre> 1874 * LocalDateTime dt = parser.parse(str, LocalDateTime::from); 1875 * </pre> 1876 * If the parse completes without reading the entire length of the text, 1877 * or a problem occurs during parsing or merging, then an exception is thrown. 1878 * 1879 * @param <T> the type of the parsed date-time 1880 * @param text the text to parse, not null 1881 * @param query the query defining the type to parse to, not null 1882 * @return the parsed date-time, not null 1883 * @throws DateTimeParseException if unable to parse the requested result 1884 */ 1885 public <T> T parse(CharSequence text, TemporalQuery<T> query) { 1886 Objects.requireNonNull(text, "text"); 1887 Objects.requireNonNull(query, "query"); 1888 try { 1889 return parseResolved0(text, null).query(query); 1890 } catch (DateTimeParseException ex) { 1891 throw ex; 1892 } catch (RuntimeException ex) { 1893 throw createError(text, ex); 1894 } 1895 } 1896 1897 /** 1898 * Fully parses the text producing an object of one of the specified types. 1899 * <p> 1900 * This parse method is convenient for use when the parser can handle optional elements. 1901 * For example, a pattern of 'uuuu-MM-dd HH.mm[ VV]' can be fully parsed to a {@code ZonedDateTime}, 1902 * or partially parsed to a {@code LocalDateTime}. 1903 * The queries must be specified in order, starting from the best matching full-parse option 1904 * and ending with the worst matching minimal parse option. 1905 * The query is typically a method reference to a {@code from(TemporalAccessor)} method. 1906 * <p> 1907 * The result is associated with the first type that successfully parses. 1908 * Normally, applications will use {@code instanceof} to check the result. 1909 * For example: 1910 * <pre> 1911 * TemporalAccessor dt = parser.parseBest(str, ZonedDateTime::from, LocalDateTime::from); 1912 * if (dt instanceof ZonedDateTime) { 1913 * ... 1914 * } else { 1915 * ... 1916 * } 1917 * </pre> 1918 * If the parse completes without reading the entire length of the text, 1919 * or a problem occurs during parsing or merging, then an exception is thrown. 1920 * 1921 * @param text the text to parse, not null 1922 * @param queries the queries defining the types to attempt to parse to, 1923 * must implement {@code TemporalAccessor}, not null 1924 * @return the parsed date-time, not null 1925 * @throws IllegalArgumentException if less than 2 types are specified 1926 * @throws DateTimeParseException if unable to parse the requested result 1927 */ 1928 public TemporalAccessor parseBest(CharSequence text, TemporalQuery<?>... queries) { 1929 Objects.requireNonNull(text, "text"); 1930 Objects.requireNonNull(queries, "queries"); 1931 if (queries.length < 2) { 1932 throw new IllegalArgumentException("At least two queries must be specified"); 1933 } 1934 try { 1935 TemporalAccessor resolved = parseResolved0(text, null); 1936 for (TemporalQuery<?> query : queries) { 1937 try { 1938 return (TemporalAccessor) resolved.query(query); 1939 } catch (RuntimeException ex) { 1940 // continue 1941 } 1942 } 1943 throw new DateTimeException("Unable to convert parsed text using any of the specified queries"); 1944 } catch (DateTimeParseException ex) { 1945 throw ex; 1946 } catch (RuntimeException ex) { 1947 throw createError(text, ex); 1948 } 1949 } 1950 1951 private DateTimeParseException createError(CharSequence text, RuntimeException ex) { 1952 String abbr; 1953 if (text.length() > 64) { 1954 abbr = text.subSequence(0, 64).toString() + "..."; 1955 } else { 1956 abbr = text.toString(); 1957 } 1958 return new DateTimeParseException("Text '" + abbr + "' could not be parsed: " + ex.getMessage(), text, 0, ex); 1959 } 1960 1961 //----------------------------------------------------------------------- 1962 /** 1963 * Parses and resolves the specified text. 1964 * <p> 1965 * This parses to a {@code TemporalAccessor} ensuring that the text is fully parsed. 1966 * 1967 * @param text the text to parse, not null 1968 * @param position the position to parse from, updated with length parsed 1969 * and the index of any error, null if parsing whole string 1970 * @return the resolved result of the parse, not null 1971 * @throws DateTimeParseException if the parse fails 1972 * @throws DateTimeException if an error occurs while resolving the date or time 1973 * @throws IndexOutOfBoundsException if the position is invalid 1974 */ 1975 private TemporalAccessor parseResolved0(final CharSequence text, final ParsePosition position) { 1976 ParsePosition pos = (position != null ? position : new ParsePosition(0)); 1977 DateTimeParseContext context = parseUnresolved0(text, pos); 1978 if (context == null || pos.getErrorIndex() >= 0 || (position == null && pos.getIndex() < text.length())) { 1979 String abbr; 1980 if (text.length() > 64) { 1981 abbr = text.subSequence(0, 64).toString() + "..."; 1982 } else { 1983 abbr = text.toString(); 1984 } 1985 if (pos.getErrorIndex() >= 0) { 1986 throw new DateTimeParseException("Text '" + abbr + "' could not be parsed at index " + 1987 pos.getErrorIndex(), text, pos.getErrorIndex()); 1988 } else { 1989 throw new DateTimeParseException("Text '" + abbr + "' could not be parsed, unparsed text found at index " + 1990 pos.getIndex(), text, pos.getIndex()); 1991 } 1992 } 1993 return context.toResolved(resolverStyle, resolverFields); 1994 } 1995 1996 /** 1997 * Parses the text using this formatter, without resolving the result, intended 1998 * for advanced use cases. 1999 * <p> 2000 * Parsing is implemented as a two-phase operation. 2001 * First, the text is parsed using the layout defined by the formatter, producing 2002 * a {@code Map} of field to value, a {@code ZoneId} and a {@code Chronology}. 2003 * Second, the parsed data is <em>resolved</em>, by validating, combining and 2004 * simplifying the various fields into more useful ones. 2005 * This method performs the parsing stage but not the resolving stage. 2006 * <p> 2007 * The result of this method is {@code TemporalAccessor} which represents the 2008 * data as seen in the input. Values are not validated, thus parsing a date string 2009 * of '2012-00-65' would result in a temporal with three fields - year of '2012', 2010 * month of '0' and day-of-month of '65'. 2011 * <p> 2012 * The text will be parsed from the specified start {@code ParsePosition}. 2013 * The entire length of the text does not have to be parsed, the {@code ParsePosition} 2014 * will be updated with the index at the end of parsing. 2015 * <p> 2016 * Errors are returned using the error index field of the {@code ParsePosition} 2017 * instead of {@code DateTimeParseException}. 2018 * The returned error index will be set to an index indicative of the error. 2019 * Callers must check for errors before using the result. 2020 * <p> 2021 * If the formatter parses the same field more than once with different values, 2022 * the result will be an error. 2023 * <p> 2024 * This method is intended for advanced use cases that need access to the 2025 * internal state during parsing. Typical application code should use 2026 * {@link #parse(CharSequence, TemporalQuery)} or the parse method on the target type. 2027 * 2028 * @param text the text to parse, not null 2029 * @param position the position to parse from, updated with length parsed 2030 * and the index of any error, not null 2031 * @return the parsed text, null if the parse results in an error 2032 * @throws DateTimeException if some problem occurs during parsing 2033 * @throws IndexOutOfBoundsException if the position is invalid 2034 */ 2035 public TemporalAccessor parseUnresolved(CharSequence text, ParsePosition position) { 2036 DateTimeParseContext context = parseUnresolved0(text, position); 2037 if (context == null) { 2038 return null; 2039 } 2040 return context.toUnresolved(); 2041 } 2042 2043 private DateTimeParseContext parseUnresolved0(CharSequence text, ParsePosition position) { 2044 Objects.requireNonNull(text, "text"); 2045 Objects.requireNonNull(position, "position"); 2046 DateTimeParseContext context = new DateTimeParseContext(this); 2047 int pos = position.getIndex(); 2048 pos = printerParser.parse(context, text, pos); 2049 if (pos < 0) { 2050 position.setErrorIndex(~pos); // index not updated from input 2051 return null; 2052 } 2053 position.setIndex(pos); // errorIndex not updated from input 2054 return context; 2055 } 2056 2057 //----------------------------------------------------------------------- 2058 /** 2059 * Returns the formatter as a composite printer parser. 2060 * 2061 * @param optional whether the printer/parser should be optional 2062 * @return the printer/parser, not null 2063 */ 2064 CompositePrinterParser toPrinterParser(boolean optional) { 2065 return printerParser.withOptional(optional); 2066 } 2067 2068 /** 2069 * Returns this formatter as a {@code java.text.Format} instance. 2070 * <p> 2071 * The returned {@link Format} instance will format any {@link TemporalAccessor} 2072 * and parses to a resolved {@link TemporalAccessor}. 2073 * <p> 2074 * Exceptions will follow the definitions of {@code Format}, see those methods 2075 * for details about {@code IllegalArgumentException} during formatting and 2076 * {@code ParseException} or null during parsing. 2077 * The format does not support attributing of the returned format string. 2078 * 2079 * @return this formatter as a classic format instance, not null 2080 */ 2081 public Format toFormat() { 2082 return new ClassicFormat(this, null); 2083 } 2084 2085 /** 2086 * Returns this formatter as a {@code java.text.Format} instance that will 2087 * parse using the specified query. 2088 * <p> 2089 * The returned {@link Format} instance will format any {@link TemporalAccessor} 2090 * and parses to the type specified. 2091 * The type must be one that is supported by {@link #parse}. 2092 * <p> 2093 * Exceptions will follow the definitions of {@code Format}, see those methods 2094 * for details about {@code IllegalArgumentException} during formatting and 2095 * {@code ParseException} or null during parsing. 2096 * The format does not support attributing of the returned format string. 2097 * 2098 * @param parseQuery the query defining the type to parse to, not null 2099 * @return this formatter as a classic format instance, not null 2100 */ 2101 public Format toFormat(TemporalQuery<?> parseQuery) { 2102 Objects.requireNonNull(parseQuery, "parseQuery"); 2103 return new ClassicFormat(this, parseQuery); 2104 } 2105 2106 //----------------------------------------------------------------------- 2107 /** 2108 * Returns a description of the underlying formatters. 2109 * 2110 * @return a description of this formatter, not null 2111 */ 2112 @Override 2113 public String toString() { 2114 String pattern = printerParser.toString(); 2115 pattern = pattern.startsWith("[") ? pattern : pattern.substring(1, pattern.length() - 1); 2116 return pattern; 2117 // TODO: Fix tests to not depend on toString() 2118 // return "DateTimeFormatter[" + locale + 2119 // (chrono != null ? "," + chrono : "") + 2120 // (zone != null ? "," + zone : "") + 2121 // pattern + "]"; 2122 } 2123 2124 //----------------------------------------------------------------------- 2125 /** 2126 * Implements the classic Java Format API. 2127 * @serial exclude 2128 */ 2129 @SuppressWarnings("serial") // not actually serializable 2130 static class ClassicFormat extends Format { 2131 /** The formatter. */ 2132 private final DateTimeFormatter formatter; 2133 /** The type to be parsed. */ 2134 private final TemporalQuery<?> parseType; 2135 /** Constructor. */ 2136 public ClassicFormat(DateTimeFormatter formatter, TemporalQuery<?> parseType) { 2137 this.formatter = formatter; 2138 this.parseType = parseType; 2139 } 2140 2141 @Override 2142 public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { 2143 Objects.requireNonNull(obj, "obj"); 2144 Objects.requireNonNull(toAppendTo, "toAppendTo"); 2145 Objects.requireNonNull(pos, "pos"); 2146 if (obj instanceof TemporalAccessor == false) { 2147 throw new IllegalArgumentException("Format target must implement TemporalAccessor"); 2148 } 2149 pos.setBeginIndex(0); 2150 pos.setEndIndex(0); 2151 try { 2152 formatter.formatTo((TemporalAccessor) obj, toAppendTo); 2153 } catch (RuntimeException ex) { 2154 throw new IllegalArgumentException(ex.getMessage(), ex); 2155 } 2156 return toAppendTo; 2157 } 2158 @Override 2159 public Object parseObject(String text) throws ParseException { 2160 Objects.requireNonNull(text, "text"); 2161 try { 2162 if (parseType == null) { 2163 return formatter.parseResolved0(text, null); 2164 } 2165 return formatter.parse(text, parseType); 2166 } catch (DateTimeParseException ex) { 2167 throw new ParseException(ex.getMessage(), ex.getErrorIndex()); 2168 } catch (RuntimeException ex) { 2169 throw (ParseException) new ParseException(ex.getMessage(), 0).initCause(ex); 2170 } 2171 } 2172 @Override 2173 public Object parseObject(String text, ParsePosition pos) { 2174 Objects.requireNonNull(text, "text"); 2175 DateTimeParseContext context; 2176 try { 2177 context = formatter.parseUnresolved0(text, pos); 2178 } catch (IndexOutOfBoundsException ex) { 2179 if (pos.getErrorIndex() < 0) { 2180 pos.setErrorIndex(0); 2181 } 2182 return null; 2183 } 2184 if (context == null) { 2185 if (pos.getErrorIndex() < 0) { 2186 pos.setErrorIndex(0); 2187 } 2188 return null; 2189 } 2190 try { 2191 TemporalAccessor resolved = context.toResolved(formatter.resolverStyle, formatter.resolverFields); 2192 if (parseType == null) { 2193 return resolved; 2194 } 2195 return resolved.query(parseType); 2196 } catch (RuntimeException ex) { 2197 pos.setErrorIndex(0); 2198 return null; 2199 } 2200 } 2201 } 2202 2203 }