11

Joda ライブラリを使用すると、次のことができます

DateTimeFormat.forPattern("yyyy").parseLocalDate("2008")

2008 年 1 月 1 日に LocalDate を作成する

Java8を使用すると、次のことができます

LocalDate.parse("2008",DateTimeFormatter.ofPattern("yyyy"))

しかし、それは解析に失敗します:

Text '2008' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2008},ISO of type java.time.format.Parsed

具体的に sth のように書く代わりに、代替手段はありますか

LocalDate.ofYearDay(Integer.valueOf("2008"), 1)

?

4

3 に答える 3

19

LocalDate解析には、年、月、日のすべてを指定する必要があります。

およびメソッドDateTimeFormatterBuilderを使用して、月と日のデフォルト値を指定できます。parseDefaulting

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

LocalDate.parse("2008", format);
于 2016-12-28T09:02:05.263 に答える
0

わかりませんでしたが、タイトルから、文字列をローカル日付に解析したいと思うので、これがその方法です

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

String date = "16/08/2016";

//convert String to LocalDate
LocalDate localDate = LocalDate.parse(date, formatter);
于 2016-12-28T08:28:33.077 に答える