将字符串解析为localdatetime

amc*_*con 0 java

将字符串解析为localdatetime时,我遇到一个奇怪的问题

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {

    public static void main(String args[])
    {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
         LocalDateTime.parse("00:00",formatter);
    }

}
Run Code Online (Sandbox Code Playgroud)

给我吗:

Exception in thread "main" java.time.format.DateTimeParseException: Text '00:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 00:00 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDateTime.parse(Unknown Source)
    at Main.main(Main.java:9)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 00:00 of type java.time.format.Parsed
    at java.time.LocalDateTime.from(Unknown Source)
    at java.time.format.Parsed.query(Unknown Source)
    ... 3 more
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {},ISO resolved to 00:00 of type java.time.format.Parsed
    at java.time.LocalDate.from(Unknown Source)
    ... 5 more
Run Code Online (Sandbox Code Playgroud)

我想将格式为"hour:minutes"的String解析为localdatetime(24H格式).我不关心月/年/日是什么,我只想要时间.

Jon*_*eet 5

我不关心月/年/日是什么,我只想要时间.

这表明你应该将它解析为a LocalTime,因为这就是字符串实际代表的内容.然后你可以添加任何LocalDate一个来获得LocalDateTime,如果你真的想假装你有更多的信息,那么你有:

import java.time.*;
import java.time.format.*;

public class Test {    
    public static void main(String args[]) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
        LocalTime time = LocalTime.parse("00:00",formatter);
        LocalDate date = LocalDate.of(2000, 1, 1);
        LocalDateTime dateTime = date.atTime(time);
        System.out.println(dateTime); // 2000-01-01T00:00
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你可以完全避免创建一个LocalDateTime并且只是使用它LocalTime,那就更好了.