Bug in java.time with Resoverstyle.STRICT [duplicate] - java

This question already has answers here:
Java 8 LocalDateTime is parsing invalid date
(5 answers)
Closed 6 years ago.
Either I don't quite grasp what the resolver style in java.time does, or there is a bug.
I have the following code (in Scala):
import java.sql.Timestamp
import java.time.format.{DateTimeFormatter, ResolverStyle}
import java.time.ZonedDateTime
val str = "2016-07-11T05:45:44.552+04:00"
val iso1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX")
val iso2 = iso1.withResolverStyle(ResolverStyle.STRICT)
Timestamp.from(ZonedDateTime.parse(str, iso1).toInstant) // works fine
Timestamp.from(ZonedDateTime.parse(str, iso2).toInstant) // nope!
The first version works and the second throws the following exception a java.time.format.DateTimeParseException. What I don't understand is why. The date and time are in my opinion valid.
See: https://docs.oracle.com/javase/8/docs/api/java/time/format/ResolverStyle.html#STRICT

This is incorrect ISO format, just use DateTimeFormatter.ISO_DATE_TIME.

Related

java.time.format.DateTimeParseException when parsing year

jdk used : 1.8
Not sure what is the issue, configuredFormat is valid one, inputTime is also valid one, really confused what is the issue.
public class Test {
public static void main(String[] args) {
String configuredFormat = "yyyyMMddHHmmssSSS";
String inputTime = "20200203164553123";
DateTimeFormatter dt = DateTimeFormatter.ofPattern(configuredFormat);
DateTimeFormatter strictTimeFormatter = dt.withResolverStyle(ResolverStyle.STRICT);
try {
LocalTime.parse(inputTime, strictTimeFormatter);
System.out.println("success");
} catch (DateTimeParseException | NullPointerException e) {
e.printStackTrace();
}
}
}
Exception I am Getting :
java.time.format.DateTimeParseException: Text '20200203164553123' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalTime.parse(LocalTime.java:441)
at com.Test.main(Test.java:20)
Lucky for you, there is an exact bug report which uses the exact same pattern that you're trying. Who better to explain than the JDK maintainers?
JDK-8031085
Workaround
DateTimeFormatter dtf = new
DateTimeFormatterBuilder()
.appendPattern("yyyyMMddHHmmss")
.appendValue(ChronoField.MILLI_OF_SECOND,3)
.toFormatter()
Adjacent value parsing is generally a hard problem. It is intended to
handle the case where the first element is variable width (the year)
and all other elements are fixed width (month, day etc). However, the
"S" pattern letter is a fraction, not a value. Specifically, the
fraction can be variable width - more or less than three digits are
possible options. Given the general case of a variable width year and
a variable width millisecond, it is not possible to determine which of
the two fields was intended to be variable.
Having said that, the implementation (and javadoc) have not ended up
as I intended. The description of "fraction" in DateTimeFormatter
describes actions in strict and lenient mode, but there is no way to
access strict or lenient mode when using
DateTimeFormatter.ofPattern(). This is a documentation bug that should
be fixed by removing the discussion of strict vs lenient.
Worse however is that the SSS pattern has therefore ended up using
strict mode when lenient mode would be appropriate. As it currently
stands, DateTimeFormatter.ofPattern("hhmmss.SSS") requires three
digits for milliseconds, when it was originally intended to require 0
to 9 (the lenient behaviour).
I tried changing the whole of the DateTimeFormatter.ofPattern() method
to use lenient parsing, and it broke no tests (which is bad in its own
way). This might be a valid fix, but only if included in JDK 8, as
once people adapt to the strict parsing it will be hard to make it
lenient.
Given that the current implementation requires three digits for SSS,
it is thus very surprising that adjacent value parsing does not apply.
Actually I agree format should be valid... this seems to be confirmed as I tried with both oracle java 8 and 9 runtime, and with java 9 it does not happen. (I tried IBM jre 8 too and it works as well)
System.out.println( System.getProperty( "java.vendor" )+" - "+System.getProperty( "java.version" ) );
String configuredFormat = "yyyyMMddHHmmssSSS";
String inputTime = "20200203164553123";
DateTimeFormatter dt = DateTimeFormatter.ofPattern(configuredFormat);
DateTimeFormatter strictTimeFormatter = dt.withResolverStyle(ResolverStyle.STRICT);
try {
//System.out.println( dt.parse( inputTime ) );
LocalTime.parse(inputTime, strictTimeFormatter);
System.out.println("success");
} catch (DateTimeParseException | NullPointerException e) {
e.printStackTrace();
}
Output
Oracle Corporation - 9.0.4
success
IBM Corporation - 1.8.0_211
success
Oracle Corporation - 1.8.0_172
java.time.format.DateTimeParseException: Text '20200203164553123' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalTime.parse(Unknown Source)
at test.Test2.main(Test2.java:19)

Implement re.search() functionality in Groovy or Java [duplicate]

This question already has answers here:
Create array of regex matches
(6 answers)
Closed 4 years ago.
I need a Groovy/Java function to search for groups in a string based on regular expression
Ex:
function("([\w-]+)-([\w.-]+)\.([\w.-]+)" ,"commons-collections-3.2.2.jar" )
should return a list ["commons-collections" , "3.2.2" , "jar"]
Python can do this by
>> import re
>> re.search("([\w-]+)-([\w.-]+)\.([\w.-]+)" ,"commons-collections-3.2.2.jar" )
>> print(result.groups())
output is ("commons-collections" , "3.2.2" , "jar")
It is a simple and basic task in groovy. Any way I hope this answer will help you.
"commons-collections-3.2.2.jar".findAll(/([\w-]+)-([\w.-]+)\.([\w.-]+)/) {
println it
}
This will produce the output :
[commons-collections-3.2.2.jar, commons-collections, 3.2.2, jar]
Update :
As #tim_yates mentioned in comment,
println "commons-collections-3.2.2.jar".findAll(/([\w-]+)-([\w.-]+)\.([\w.-]+)/) { it.tail() }
This provides better output than above and also more specific to the task.
Output:
[[commons-collections, 3.2.2, jar]]

Bug in Finnish date localization?

I'm trying to localize for Finland using this code:
Locale finLocale = new Locale("fi", "FI");
Date today = new Date(2017, 1, 1);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG, finLocale);
String formattedDate = dateFormat.format(today);
System.out.println(formattedDate);
What I end up getting is "helmikuutata". I would expect "helmikuu" or "helmikuuta", but this just seems wrong.
Is this valid Finnish, or is there a bug in Java? My version is 1.8.0_31
Yes, this was a bug in JDK (See JDK-8074791), wherein an extra 'ta' was appended to the month name. This got fixed from JDK 8u60 version onwards. So, if you upgrade to latest JDK versions like JDK8u131, you will get the correct output.
I am convinced that the answer by Pallavi Sonal is correct. I have already upvoted it and you should probably accept it. I had wanted to keep the following a comment, but it deserves better formatting, so here goes.
java.time
Since you are using Java 8 (and even if you didn’t), you will prefer the modern more programmer friendly API of java.time:
LocalDate today = LocalDate.of(2017, Month.FEBRUARY, 1);
DateTimeFormatter dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
.withLocale(finLocale);
String formattedDate = today.format(dateFormat);
On my Java 1.8.0_131 it gives the expected
1. helmikuuta 2017
If someone reading this is using Java 6 or 7, please consider getting the ThreeTen Backport library so you can use the modern date and time API as shown.

DateTimeFormatter pattern with liternal and no separator does not work

The parser generated by DateTimeFormatter.ofPattern exhibits the following interesting behaviour which is preventing me from writing a pattern to parse a string like 20150100:
System.out.println(DateTimeFormatter.ofPattern("yyyyMM").parse("201501", YearMonth::from)); // works
System.out.println(DateTimeFormatter.ofPattern("yyyyMM'aa'").parse("201501aa", YearMonth::from)); // works
System.out.println(DateTimeFormatter.ofPattern("yyyyMM'00'").parse("20150100", YearMonth::from));
// java.time.format.DateTimeParseException: Text '20150100' could not be parsed at index 0
I debuged the code, it seems the problem is caused by the year field parsing beyond the end of the string (max width for three y's and more is always 19). However, I don't understand how it could work for the pattern without the '00' literal at the end.
Is there any way to fix this withing having to use a formatter builder?
Edit:
Since Jarrod below confirmed it's buggy, I did more googling and finally found the bug reports:
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8031085
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8032491
Both are only fixed in Java 9 though......
There is a bug in the DateTimePrinterParser:
I step debugged all the way through it, apparently you can not have digits as literals. Similar test codes proves this if you step debug all the way through to the DateTimeFormatterBuilder.parse() method you can see what it is doing wrong.
Apparently the Value(YearOfEra,4,19,EXCEEDS_PAD) parser consumes the 00 where they stop if those are not digits because it is looking for a number 4 to 19 digits long. The DateTimeFormatter that is embedded in the DateTimeParseContext is wrong.
If you put a non-digit character literal like xx it works, digit literals don't.
Both of these fail:
final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM'00'");
System.out.println(sdf.parse("20150100"));
Exception in thread "main" java.text.ParseException: Unparseable date:
"20150100" at java.text.DateFormat.parse(DateFormat.java:366)
final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMM'00'");
System.out.println(dateTimeFormatter.parse("20150100", YearMonth::from));
Exception in thread "main" java.time.format.DateTimeParseException:
Text '20150100' could not be parsed at index 0 at
java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at
java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
Both of these succeed:
final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM'xx'");
System.out.println(sdf.parse("201501xx"));
Thu Jan 01 00:00:00 EST 2015
final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMM'xx'");
System.out.println(dateTimeFormatter.parse("201501xx", YearMonth::from));
2015-01
If you don't mind to use a 3rd-party-library then you might try my library Time4J whose newest version v4.18 can do what you wish:
import net.time4j.Month;
import net.time4j.range.CalendarMonth;
import net.time4j.format.expert.ChronoFormatter;
import net.time4j.format.expert.PatternType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.text.ParseException;
import java.util.Locale;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
#RunWith(JUnit4.class)
public class CalendarMonthTest {
#Test
public void parse2() throws ParseException {
assertThat(
ChronoFormatter.ofPattern(
"yyyyMM'00'",
PatternType.CLDR,
Locale.ROOT,
CalendarMonth.chronology()
).parse("20150100"),
is(CalendarMonth.of(2015, Month.JANUARY)));
}
}
By the way, the links to the JDK-bug-log are not really related to your problem. Those issues only describe problems when applying adjacent digit parsing in context of fractional seconds. While that problem will be fixed with Java-9, your problem will not. Maybe you wish to open a new issue there? But I doubt that Oracle will treat it as bug. It is rather a new feature not supported until now by any library distributed by Oracle. Literals with (leading) digits are not expected in JSR-310 (aka java.time-package) to take part into adjacent-value-parsing (and in SimpleDateFormat also not).
Side note: Time4J is not just an answer to this detail (digit literals) but generally offers better performance in parsing and can be used in parallel with JSR-310 due to a lot of conversion methods. For example: To achieve an instance of YearMonth, just call calendarMonth.toTemporalAccessor() on the parsed result.
As an addendum to user177800's answer, you can use this form instead:
var formatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.appendValue(ChronoField.MONTH_OF_YEAR, 2)
.appendLiteral("00")
.toFormatter();
YearMonth.parse("20220200", formatter);
All part of java.time.

Joda Time resource not found error [duplicate]

This question already has answers here:
Only some users reporting "Resource Not Found" error. Does this make sense?
(4 answers)
Closed 7 years ago.
I'm trying to take a String and convert it to another String in a more readable format:
String startTime = invite.get_start_time();
Log.d(LOG_TAG, "String to be converted is " + startTime);
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dt = fmt.parseDateTime(startTime);
invite.set_start_time(dt.toString("MM dd yyyy hh:mmaa"));
08-02 14:33:19.011: D/InvitesObjectListAdapter(856): String to be
converted is 2015-08-03 10:30:00 08-02 14:33:19.041:
W/System.err(856): java.io.IOException: Resource not found:
"org/joda/time/tz/data/ZoneInfoMap" ClassLoader:
dalvik.system.PathClassLoader[DexPathList[[zip file
"/data/app/me.lunchbunch.core-1/base.apk"],nativeLibraryDirectories=[/vendor/lib64,
/system/lib64]]]
Anyone know where this error comes from?
Sorry for wasting peoples' times, #adelphus is correct - I did not initialize with:
JodaTimeAndroid.init(this);
It was in my code, but I need to refactor to ensure this is hit.

Categories

Resources