java - 使用 DateTimeFormatterBuilder 将 String 解析为 LocalDateTime 时如何防止自动生成 'T' 字母

标签 java datetime java-8 datetime-format

我有这段代码可以将字符串双向解析为 LocalDateTime:

public class ConvertLocalDateToString {

private static final DateTimeFormatter CUSTOM_LOCAL_DATE;
static {
    CUSTOM_LOCAL_DATE = new DateTimeFormatterBuilder()
            .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
            .appendLiteral('-')
            .appendValue(MONTH_OF_YEAR, 2)
            .appendLiteral('-')
            .appendValue(DAY_OF_MONTH, 2)
            .appendLiteral(' ')
            .appendValue(HOUR_OF_DAY, 2)
            .appendLiteral(':')
            .appendValue(MINUTE_OF_HOUR, 2)
            .optionalStart()
            .appendLiteral(':')
            .appendValue(SECOND_OF_MINUTE, 2)
            .toFormatter();
}

public static void main(String[] args) {

    String str = "2020-02-18 15:04:30";
    LocalDateTime dateTime = LocalDateTime.parse(str, CUSTOM_LOCAL_DATE); //2020-02-18T15:04:30

    LocalDateTime addedDateTime = LocalDateTime.parse(dateTime.plusHours(10).format(CUSTOM_LOCAL_DATE.withZone(ZoneOffset.UTC)));
    System.out.println(addedDateTime);
    System.out.println(dateTime); //2020-02-18T15:04:30

}

我的假设是“T”字母是由 ISO-8601 格式自动生成的。这导致:

DateTimeParseException: Text '2020-02-18 15:04:30' could not be parsed at index 10

如何摆脱它?

最佳答案

System.out.println(dateTime)System.out.println(String.valueOf(dateTime)) 相同。

String.valueOf(dateTime)dateTime.toString() 相同,只是它可以处理 null 值。

LocalDateTime 上调用 toString()documented为此:

Outputs this date-time as a String, such as 2007-12-03T10:15:30.

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.

如果您需要不同的格式,请调用format(DateTimeFormatter formatter) .

<小时/>

那么,回答你的问题:

My assumption is 'T' letter is auto-generated by ISO-8601 format.

T 并不比 -: 字符更自动生成。

How do I get rid of it?

调用format(...)并指定您想要的格式,例如

System.out.println(dateTime.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")));

关于java - 使用 DateTimeFormatterBuilder 将 String 解析为 LocalDateTime 时如何防止自动生成 'T' 字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60312178/

相关文章:

java - 术语:如何谈论 Java 中的指针和引用

java - 时间戳解析失败

php - 转换 DateTime 时遇到格式不正确的数值

java - 如果过滤条件是多个且动态出现,则从列表中过滤对象

java - ConstraintLayout 指南百分比动画

java - 痛饮 : How to rename generated Java code according to a regex?

java - java中的日期类型填充MySQL数据库

java - 将 MySql 日期时间映射到 hibernate

java-8 - 为什么需要在管道中进行短路操作...在 Java 8 中

java - 如何过滤映射并返回值列表