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