我正在尝试将字符串FEBRUARY 2019解析为一个LocalDate。
这是我的方法:
LocalDate month = LocalDate.parse("FEBRUARY 2019", DateTimeFormatter.ofPattern("MMMM yyyy"));或者设置Locale.US
LocalDate month = LocalDate.parse("FEBRUARY 2019", DateTimeFormatter.ofPattern("MMMM yyyy", Locale.US));但我得到的只是以下例外:
Exception in thread "main" java.time.format.DateTimeParseException: Text 'FEBRUARY 2019' could not be parsed at index 0发布于 2019-02-08 10:20:54
首先,我建议你得到的输入不是一个日期,而是一年和一个月。所以解析到一个YearMonth,然后根据需要创建一个LocalDate。我发现最简单的做法是,使文本处理代码只处理文本处理,并在您已经处于日期/时间域中时分别执行任何其他转换。
要处理区分大小写的问题,可以创建一个不区分大小写的解析DateTimeFormatter。下面是一个完整的例子:
import java.time.*;
import java.time.format.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
// Note: this would probably be a field somewhere so you don't need
// to build it every time.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MMMM yyyy")
.toFormatter(Locale.US);
YearMonth month = YearMonth.parse("FEBRUARY 2019", formatter);
System.out.println(month);
}
}作为另一种方法,如果您有不同的表示,可以使用它,您可以构建一个映射并将它传递给DateTimeFormatterBuilder.appendText。(我只是在不知何故把代码搞砸的时候才发现这一点的。)
import java.time.*;
import java.time.format.*;
import java.time.temporal.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
// TODO: Build this map up programmatically instead?
Map<Long, String> monthNames = new HashMap<>();
monthNames.put(1L, "JANUARY");
monthNames.put(2L, "FEBRUARY");
monthNames.put(3L, "MARCH");
monthNames.put(4L, "APRIL");
monthNames.put(5L, "MAY");
monthNames.put(6L, "JUNE");
monthNames.put(7L, "JULY");
monthNames.put(8L, "AUGUST");
monthNames.put(9L, "SEPTEMBER");
monthNames.put(10L, "OCTOBER");
monthNames.put(11L, "NOVEMBER");
monthNames.put(12L, "DECEMBER");
// Note: this would probably be a field somewhere so you don't need
// to build it every time.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.MONTH_OF_YEAR, monthNames)
.appendLiteral(' ')
.appendPattern("yyyy")
.toFormatter(Locale.US);
YearMonth month = YearMonth.parse("FEBRUARY 2019", formatter);
System.out.println(month);
}
}发布于 2019-02-08 10:31:27
正如Jon所指出的,您没有一个完整的日期可以解析,并且可以使用YearMonth。另一种选择是指定默认日期。
与提供月份名称映射的方法不同,您还可以简单地使用一个库(如WordUtils )将输入转换为正确的格式,例如:
final LocalDate month = LocalDate.parse(
org.apache.commons.text.WordUtils.capitalizeFully("FEBRUARY 2019"),
new DateTimeFormatterBuilder()
.appendPattern("MMMM uuuu")
.parseCaseInsensitive()
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter(Locale.US));https://stackoverflow.com/questions/54590045
复制相似问题