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