我正在尝试将字符串 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
最佳答案
首先,我建议您输入的不是日期 - 它是年和月。因此,解析为 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);
}
}
如果您有不同的表示,作为一种可能有用的替代方法,您可以构建一个 map 并将其传递给 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);
}
}
关于java - 将大写日期解析为 LocalDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590045/