java - Importance of order when using multiple optional patterns -
how order of optional patterns in datetimeformatter
affect parsing operation?
i running program , wondered why last line throws exception not first three.
public static void main(string[] args) { string p1 = "[eeee][e] dd-mm-yyyy"; string p2 = "[e][eeee] dd-mm-yyyy"; string date1 = "thu 07-01-2016"; string date2 = "thursday 07-01-2016"; parse(date1, p1); //ok parse(date1, p2); //ok parse(date2, p1); //ok parse(date2, p2); //exception } private static void parse(string date, string pattern) { datetimeformatter fmt = datetimeformatter.ofpattern(pattern, locale.english); system.out.println(fmt.parse(date)); }
the exception on last line is:
java.time.format.datetimeparseexception: text 'thursday 07-01-2016' not parsed @ index 3
the documentation not mention precedence , i'll argue result getting normal. result of reading string format left right.
let's consider first format
"[eeee][e] dd-mm-yyyy"
."thu 07-01-2016"
: api tries find if first optional section"[eeee]"
can matched. quotingdatetimeformatter
javadoc text tokenexactly 4 pattern letters use full form.
which in case full form of day of week. doesn't match
"thu"
optional section skipped. second optional section, however,"[e]"
, , still quotingless 4 pattern letters use short form.
so match
"thu"
. string parse can understood correctly"thursday 07-01-2016"
: same above, except match on first optional section"thursday"
. api still continue search valid section next optional,"[e]"
, won't find optional section skipped.
- let's consider second format
"[e][eeee] dd-mm-yyyy"
."thu 07-01-2016"
: api tries find if first optional section"[e]"
can matched , work"thu"
. above, api try find match"[eeee]"
won't find optional section skipped."thursday 07-01-2016"
: api tries match"[e]"
again , that's thing happens: match."thursday"
starts"thu"
formatter able find match. then, tries parse rest"rsday 07-01-2016"
.[eeee]
optional section won't matched skipped. fails space because there no space on what's left (there's"r"
instead).
so if run code
parse("thuthursday 07-01-2016", "[e][eeee] dd-mm-yyyy");
you'll see works: "[e]"
matched "thu"
, "[eeee]"
matched "thursday"
.
notice how exception message hints @ (emphasis mine):
java.time.format.datetimeparseexception: text 'thursday 07-01-2016' not parsed at index 3
index 3 corresponds "r"
of "rsday"
means able parse, right point.
Comments
Post a Comment