Issue
I have been working on a project that requires me to parse a string in this manner i have seperated out the small part that has been throwing errors,
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
public class TestingYearMonth {
public static void main(String[] args) {
YearMonth yearMonth = YearMonth.parse("Feb-17", DateTimeFormatter.ofPattern("MMM-yy"));
System.out.println(yearMonth.getMonth() + " " + yearMonth.getYear());
}
}
my teacher runs the exact same code and it returns an output no problem. but when i run it i get the following error
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Feb-17' could not be parsed at index 0
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.YearMonth.parse(YearMonth.java:295)
at com.ethanbradley.assignment6.TestingYearMonth.main(TestingYearMonth.java:10)
we checked and my jdk is fine (jdk 11, the amazon coretto version) i really cannot see why this does not work, please help oh wise internet people....
Solution
Specify a Locale
Likely that the default locale of your JVM is not one that recognizes “Feb” as month of February.
Specify a Locale
to determine the human language and cultural norms to be used in parsing the name of month.
Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM-yy" , locale ) ;
YearMonth yearMonth = YearMonth.parse( "Feb-17" , f );
See this code run live at IdeOne.com.
ISO 8601
Using localized text for data-exchange is unwise. I suggest you educate the publisher of your data about the ISO 8601 standard formats for exchanging date-time values as text.
The standard format for year-month is YYYY-MM. Example: 2017-02
.
The java.time classes use ISO 8601 formats by default.
YearMonth.parse( "2017-02" )
Answered By - Basil Bourque
Answer Checked By - Robin (JavaFixing Admin)