使用 Java8 将年份字符串解析为 LocalDate
Parsing a year String to a LocalDate with Java8
有了 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
有什么替代方法,而不是像这样专门写某事
LocalDate.ofYearDay(Integer.valueOf("2008"), 1)
?
我没听懂
但从标题来看,我认为你想将一个字符串解析为一个本地日期,所以你就是这样做的
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");
String date = "16/08/2016";
//convert String to LocalDate
LocalDate localDate = LocalDate.parse(date, formatter);
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);
String yearStr = "2008";
Year year = Year.parse(yearStr);
System.out.println(year);
输出:
2008
如果您需要一种表示年份的方式,那么 LocalDate
不适合您的目的 class。 java.time
包含一个 Year
class 完全适合您。请注意,我们甚至不需要显式格式化程序,因为显然您的年份字符串是一年的默认格式。如果以后您想转换,那也很容易。要转换为一年的第一天,就像 Joda-Time 会给你的那样:
LocalDate date = year.atDay(1);
System.out.println(date);
2008-01-01
如果您发现以下内容更具可读性,请改用它:
LocalDate date = year.atMonth(Month.JANUARY).atDay(1);
结果是一样的
如果您从一开始就需要 LocalDate
, 是正确的,您应该使用它。
有了 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
有什么替代方法,而不是像这样专门写某事
LocalDate.ofYearDay(Integer.valueOf("2008"), 1)
?
我没听懂 但从标题来看,我认为你想将一个字符串解析为一个本地日期,所以你就是这样做的
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");
String date = "16/08/2016";
//convert String to LocalDate
LocalDate localDate = LocalDate.parse(date, formatter);
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);
String yearStr = "2008";
Year year = Year.parse(yearStr);
System.out.println(year);
输出:
2008
如果您需要一种表示年份的方式,那么 LocalDate
不适合您的目的 class。 java.time
包含一个 Year
class 完全适合您。请注意,我们甚至不需要显式格式化程序,因为显然您的年份字符串是一年的默认格式。如果以后您想转换,那也很容易。要转换为一年的第一天,就像 Joda-Time 会给你的那样:
LocalDate date = year.atDay(1);
System.out.println(date);
2008-01-01
如果您发现以下内容更具可读性,请改用它:
LocalDate date = year.atMonth(Month.JANUARY).atDay(1);
结果是一样的
如果您从一开始就需要 LocalDate
,