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