tl;dr
Parse as a MonthDay
rather than LocalDate
.
MonthDay.parse(
"Jan 15" ,
DateTimeFormatter.ofPattern( "MMM dd" , Locale.US )
)
--01-15
MonthDay
Your input lacks a year, so it cannot be parsed as a LocalDate
. Instead, parse as a MonthDay
.
If you are parsing a string that represent a month-day, use a class that represents month-day values. That class would be MonthDay
.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM dd" , Locale.US ) ;
String input = "Jan 15" ;
MonthDay md = MonthDay.parse( input , f ) ;
md.toString(): --01-15
That double-hyphen in the generated output string follows the ISO 8601 standard, indicating the year is unknown/omitted.
LocalDate
You can assign a year if known.
LocalDate ld = md.atYear( 2017 ) ;
ld.toString(): 2017-01-15
See this code run live at IdeOne.com.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.