LocalDateTime.toString - 可以在环境中配置格式吗?

LocalDateTime.toString - can the format be configured in the environment?

我有使用 myTime.toString 将 LocalDateTime 保存为字符串的代码。它在使用 Spring 转换器从 String 转换为 LocalDateTime 时被读回。没有任何格式,设置为使用系统默认设置。

在一个环境中读取它,因为默认格式似乎不正确(2019-03-01T11:51:07.017)

Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalDateTime] for value '2020-01-13T07:00'; nested exception is java.time.format.DateTimeParseException: Text '2020-01-13T07:00' could not be parsed at index 16

这个 属性 是否有任何系统范围的配置,或者我应该在所有地方明确格式化?

Is there any system-wide configuration of this property …

没有

LocalDateTime.toString()产生的格式是固定的,你不能改变,无论如何都不能。来自文档:

The output will be one of the following ISO-8601 formats:

  • uuuu-MM-dd'T'HH:mm
  • uuuu-MM-dd'T'HH:mm:ss
  • uuuu-MM-dd'T'HH:mm:ss.SSS
  • uuuu-MM-dd'T'HH:mm:ss.SSSSSS
  • uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

因此,您可以影响格式的唯一方法是控制您是否有秒或秒的分数 LocalDateTime

… or should I just explicitly format everywhere?

我不确定这是否对您有帮助。正如 Andreas 在评论中所说,单参数 LocalDateTime.parse() 可以很好地解析 2020-01-13T07:002019-03-01T11:51:07.017。对于您的问题,我能想到的唯一解释是使用了默认格式化程序以外的其他格式化程序进行解析。

Link