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