我只是想在Java 8中将日期字符串转换为DateTime对象。运行以下几行代码:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime dt = LocalDateTime.parse("20140218", formatter);

我得到以下错误:

Exception in thread "main" java.time.format.DateTimeParseException: 
Text '20140218' could not be parsed: 
Unable to obtain LocalDateTime from TemporalAccessor: 
{},ISO resolved to 2014-02-18 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)

语法与这里建议的完全相同,但是我遇到了一个异常。我使用的是JDK-8u25。


当前回答

这很好

public class DateDemo {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm");
        String date = "16-08-2018 12:10";
        LocalDate localDate = LocalDate.parse(date, formatter);
        System.out.println("VALUE="+localDate);

        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
        LocalDateTime parse = LocalDateTime.parse(date, formatter1);
        System.out.println("VALUE1="+parse);
    }
}

输出:

VALUE=2018-08-16
VALUE1=2018-08-16T12:10

其他回答

对于值得的是,如果有人应该再次阅读这个主题(像我一样),正确的答案将在DateTimeFormatter定义中,例如:

private static DateTimeFormatter DATE_FORMAT =  
            new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]")
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter(); 

如果将出现可选字段,则应该设置可选字段。其余的代码应该完全相同。

编辑:有用的东西从wittyameta评论:

记住在调用appendPattern之后添加parsedefaults。否则它会给出DateTimeParseException

试试这个:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy"); 
LocalDate fromLocalDate = LocalDate.parse(fromdstrong textate, dateTimeFormatter);

你可以添加任何你想要的格式。这对我很有用!

如果你真的需要将日期转换为LocalDateTime对象,你可以使用LocalDate.atStartOfDay()。这将给你一个指定日期的LocalDateTime对象,将小时、分钟和秒字段设置为0:

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime time = LocalDate.parse("20140218", formatter).atStartOfDay();
 DateTimeFormatter format = new DateTimeFormatterBuilder()
                            .appendPattern("yyyy-MM-dd")
                            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                            .parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
                            .toFormatter();

对我有用

我遇到这个问题是因为我的输入字符串中没有年份:

输入字符串:周二,6月8日10:00 PM 格式化程序:DateTimeFormatter。ofPattern("EEEE, mm d 'at' h:mm a", Locale.US);

我知道年份,所以我只是把它附加到:

输入字符串:2021年6月8日星期二下午6:30 格式化程序:DateTimeFormatter。ofPattern("EEEE, mm d 'at' h:mm a uuuu", Locale.US);