【问题标题】:Parse string to localdatetime将字符串解析为本地日期时间
【发布时间】:2016-07-23 13:03:01
【问题描述】:

将字符串解析为本地日期时间时遇到一个奇怪的问题

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

我想将格式为“小时:分钟”的字符串解析为本地日期时间(24 小时格式)。我不在乎分配什么月/年/日,我只想要时间。

【问题讨论】:

  • 您的数据“00:00”似乎与 ISO_LOCAL_TIME 规定的格式不兼容。

标签: java


【解决方案1】:

我不在乎分配什么月/年/日,我只想要时间。

这表明您应该将其解析为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,那就更好了。

【讨论】:

  • 哦,我不知道 LocalTime 类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
  • 2016-02-27
  • 2021-06-10
  • 2012-01-28
  • 2019-09-14
相关资源
最近更新 更多