【问题标题】:Cannot parse threeten datetime to a specific format [duplicate]无法将三个日期时间解析为特定格式[重复]
【发布时间】:2020-04-14 08:17:37
【问题描述】:

我正在尝试格式化 Threeten 日期时间,从 yyyy-MM-dd'T'HH:mm:ssyyyy-MM-dd HH:mm:ss。下面是我用来完成任务的代码。

public void testChangeFormat() {
    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime date1 = LocalDateTime.parse("2020-03-10T15:14:05", inputFormatter);
    System.out.println(date1); // prints 2020-03-10T15:14:05
    String formattedDate = outputFormatter.format(date1);
    System.out.println(formattedDate); // prints 2020-03-10 15:14:05
    LocalDateTime newFormattedDateTime = LocalDateTime.parse(formattedDate);
    System.out.println(newFormattedDateTime);
}

在我尝试将 formattedDate 解析为 LocalDateTime 之前,一切似乎都按预期工作,LocalDateTime newFormattedDateTime = LocalDateTime.parse(formattedDate);

我什至使用 outputFormatter 将日期时间格式化为 2020-03-10 15:14:05,但是当我尝试将其解析为 LocalDateTime 时,它​​给了我以下异常:

org.threeten.bp.format.DateTimeParseException: Text '2020-03-10 15:14:05' could not be parsed at index 10

有人可以帮我解决这个问题吗?

【问题讨论】:

标签: java datetime


【解决方案1】:

LocalDateTime.parse(formattedDate) 正在使用DateTimeFormatter.ISO_LOCAL_DATE_TIME(即格式yyyy-MM-dd'T'HH:mm:ss)。这就是为什么在尝试解析格式为 yyyy-MM-dd HH:mm:ss 的字符串时会出现异常的原因。你应该使用:

LocalDateTime.parse(formattedDate, outputFormatter) 如果您出于某种原因再次对LocalDateTime 进行解析。

注意: 你的打印格式是:outputFormatter.format(date1) 对吗?

【讨论】:

  • 使用LocalDateTime.parse(formattedDate, outputFormatter) 给了我像2020-03-10T15:14:05这样的日期时间
  • 你到底想要什么?你在这条线上有你想要的格式outputFormatter.format(date1) 对吗?
  • outputFormatter.format(date1) 在字符串中有我想要的日期时间格式,我想将其解析为实际的日期时间。
  • 你已经在你的第三行 LocalDateTime date1 = LocalDateTime.parse("2020-03-10T15:14:05", inputFormatter); 或者你想要它到 ZonedDateTime 还是什么? (LocalDateTime 是当前时区的 DateTime)
【解决方案2】:

您似乎对LocalDateTime 和格式(这是一种字符串表示形式)感到困惑。

当您使用System.out.println(隐式调用toString,您很可能已经知道)打印其对象时,LocalDateTime 中始终包含T,例如

System.out.println(LocalDateTime.now());

将输出2020-04-14T09:36:04.723994

请看下面LocalDateTimetoString 是如何实现的:

@Override
public String toString() {
    return date.toString() + 'T' + time.toString();
}

因此您的以下语句将始终在其中显示'T'

System.out.println(newFormattedDateTime);

您可以将LocalDateTime 格式化为您选择的String 表示。正如我在第一行中提到的,格式是字符串,即您将LocalDateTime 格式化为String 表示形式,您可以在其中应用DateTimeFormatter 提供的所有选项。

formattedDate 转换为LocalDateTime 的正确方法是应用outputFormatter 中指定的相应格式。

LocalDateTime newFormattedDateTime = LocalDateTime.parse(formattedDate,outputFormatter);

日期和时间如何存储在LocalDateTime 对象中不应成为问题。我们总是可以从中创建所需格式的字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多