How to prevent auto-generated 'T' letter when parsing String to LocalDateTime using DateTimeFormatterBuilder [duplicate]

随声附和 提交于 2020-06-29 04:23:08

问题


I have this fragment of code to bidirectional parsing String to 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

}

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

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

How do I get rid of it?


回答1:


System.out.println(dateTime) is the same as System.out.println(String.valueOf(dateTime)).

String.valueOf(dateTime) is the same as dateTime.toString(), except it can handle null value.

Calling toString() on a LocalDateTime is documented to do this:

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.

If you want different format, call format(DateTimeFormatter formatter).


So, to answer your questions:

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

The T is no more auto-generated than the - and : characters.

How do I get rid of it?

Call format(...) and specify the format you want, e.g.

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


来源:https://stackoverflow.com/questions/60312178/how-to-prevent-auto-generated-t-letter-when-parsing-string-to-localdatetime-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!