字符串到LocalDate

cla*_*l3r 92 java jodatime

如何将字符串转换为LocalDate

我见过的例子如下:

LocalDate dt = new LocalDate("2005-11-12");
Run Code Online (Sandbox Code Playgroud)

但我的字符串如下:

2005-nov-12
Run Code Online (Sandbox Code Playgroud)

her*_*tzi 170

java.time

从Java 1.8开始,您可以使用java.time类在没有额外库的情况下实现此目的.请参阅教程.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
formatter = formatter.withLocale( putAppropriateLocaleHere );  // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
LocalDate date = LocalDate.parse("2005-nov-12", formatter);
Run Code Online (Sandbox Code Playgroud)

但语法几乎相同.

  • 这是因为你的默认Locale,预计"月"的"N"是大写. (3认同)

fge*_*fge 71

当您使用Joda Time时,您应该使用DateTimeFormatter:

final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);
Run Code Online (Sandbox Code Playgroud)

如果使用Java 8或更高版本,请参阅hertzi的答案


Spe*_*mos 14

您可能必须从DateTime转到LocalDate.

DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MMM-dd");
DateTime dateTime = FORMATTER.parseDateTime("2005-nov-12");
LocalDate localDate = dateTime.toLocalDate();
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这个答案指的是 Joda,而不是 Java SE。 (3认同)

Cha*_*har 8

日期时间格式由org.joda.time.format.DateTimeFormatter class.执行.三个类提供工厂方法来创建格式化程序,这是一个.其他人是ISODateTimeFormatDateTimeFormatterBuilder.

DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MMM-dd");
LocalDate lDate = new LocalDate().parse("2005-nov-12",format);
Run Code Online (Sandbox Code Playgroud)

final org.joda.time.LocalDate class是一个不可变的日期时间类,表示没有时区的日期.如果按时间顺序排列,LocalDate线程安全且不可变的.提供的所有标准年表类都是线程安全且不可变的.


小智 5

DateTimeFormatter 具有可直接用于解析字符序列的内置格式。区分大小写,Nov 可以工作,但是 nov 和 NOV 不起作用:

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");

try {
    LocalDate datetime = LocalDate.parse(oldDate, pattern);
    System.out.println(datetime); 
} catch (DateTimeParseException e) {
    // DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
    // Exception handling message/mechanism/logging as per company standard
}
Run Code Online (Sandbox Code Playgroud)

DateTimeFormatterBuilder提供创建格式化程序的自定义方法。不区分大小写,Nov 、 nov 和 NOV 将被视为相同。

DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
        .append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
    LocalDate datetime = LocalDate.parse(oldDate, f);
    System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
     // Exception handling message/mechanism/logging as per company standard
}
Run Code Online (Sandbox Code Playgroud)

  • 欢迎来到 SO,我们感谢您的意见!请编辑您的答案并提供更多解释,它与问题有何关系,您从哪里获得解决方案,为什么它有效?有关更多指导,请参阅 https://stackoverflow.com/help/how-to-answer (2认同)