Parsing a year String to a LocalDate with Java8

流过昼夜 提交于 2019-11-30 20:13:25

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 the parseDefaulting methods:

DateTimeFormatter format = new DateTimeFormatterBuilder()
     .appendPattern("yyyy")
     .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
     .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
     .toFormatter();

LocalDate.parse("2008", format);
    String yearStr = "2008";
    Year year = Year.parse(yearStr);
    System.out.println(year);

Output:

2008

If what you need is a way to represent a year, then LocalDate is not the correct class for your purpose. java.time includes a Year 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:

    LocalDate date = year.atDay(1);
    System.out.println(date);

2008-01-01

In case you find the following more readable, use that instead:

    LocalDate date = year.atMonth(Month.JANUARY).atDay(1);

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.

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

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");

String date = "16/08/2016";

//convert String to LocalDate
LocalDate localDate = LocalDate.parse(date, formatter);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!