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