将字符串解析为localdatetime

时间:2016-07-23 13:03:01

标签: 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);
    }

}

给我:

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

我想用格式解析一个字符串"小时:分钟"到localdatetime(24H格式)。我不在乎什么月/年/日被认定,我只想要时间。

1 个答案:

答案 0 :(得分:5)

  

我不在乎什么月/年/日被认定,我只想要时间。

这表明你将其解析为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
    }
}

如果您可以完全避免创建LocalDateTime并且只使用LocalTime,那就更好了。