With Joda library, you can do
DateTimeFormat.forPattern("yyyy").parseLocalDate("2008")
that creates a LocalDate at Jan 1st, 2008
With Java8, you can try to do
LocalDate.parse("2008",DateTimeFormatter.ofPattern("yyyy"))
but that fails to parse:
Text '2008' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2008},ISO of type java.time.format.Parsed
Is there any alternative, instead of specifically writing sth like
LocalDate.ofYearDay(Integer.valueOf("2008"), 1)
?
I didn't get you but from the title I think you want to parse a String to a localdate so this is how you do it
Output:
If what you need is a way to represent a year, then
LocalDate
is not the correct class for your purpose.java.time
includes aYear
class exactly for you. Note that we don’t even need an explicit formatter since obviously your year string is in the default format for a year. And if at a later point you want to convert, that’s easy too. To convert into the first day of the year, like Joda-Time would have given you:In case you find the following more readable, use that instead:
The result is the same.
If you do need a
LocalDate
from the outset, greg449’s answer is correct and the one that you should use.LocalDate
parsing requires that all of the year, month and day are specfied.You can specify default values for the month and day by using a
DateTimeFormatterBuilder
and using theparseDefaulting
methods: