What is the equivalent format string of DateTimeFormatter.ISO_OFFSET_DATE_TIME?

可紊 提交于 2019-12-22 08:29:34

问题


Do we know if there is an equivalent format string that outputs the same result as DateTimeFormatter.ISO_OFFSET_DATE_TIME?

i.e.

ZonedDateTime dateTime = ZonedDateTime.now();
System.out.println(dateTime.format(DateTimeFormatter.ofPattern(pattern)));
System.out.println(dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

would output the same


回答1:


No, this is not possible

On request: Yes, we know that there is no equivalent format pattern string of DateTimeFormatter.ISO_OFFSET_DATE_TIME.

DateTimeFormatter.ISO_OFFSET_DATE_TIME omits the seconds and/or nano of second if they are zero. If the nanos are non-zero “As many digits will be output as required.” There is no pattern letter or combination of pattern letters that will give you the same behaviour.

Deep inside DateTimeFormatter, ISO_OFFSET_DATE_TIME uses an ISO_LOCAL_TIME, which in turn is defined in this way:

    ISO_LOCAL_TIME = new DateTimeFormatterBuilder()
            .appendValue(HOUR_OF_DAY, 2)
            .appendLiteral(':')
            .appendValue(MINUTE_OF_HOUR, 2)
            .optionalStart()
            .appendLiteral(':')
            .appendValue(SECOND_OF_MINUTE, 2)
            .optionalStart()
            .appendFraction(NANO_OF_SECOND, 0, 9, true)
            .toFormatter(ResolverStyle.STRICT, null);

Which is the way to obtain the dynamic behaviour: using a DateTimeFormatterBuilder and its optionalStart and appendFraction methods.

As an aside, you don’t want to copy the behaviour of ISO_OFFSET_DATE_TIME exactly. You will want to use the built-in formatter.




回答2:


This worked for me:

    ZonedDateTime dateTime = ZonedDateTime.now();
    System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")));
    System.out.println(dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

2018-10-03T07:24:14.772+03:00 
2018-10-03T07:24:14.772+03:00

Though it will not always produce the same result because ISO_OFFSET_DATE_TIME prints fraction of second with different length depending on nanos value, while .SSS has fixed lengh = 3

     ZonedDateTime dateTime = ZonedDateTime.of(2001, 1, 1, 0, 0, 0, 1, ZoneId.systemDefault());
     System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")));
     System.out.println(dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));   

     2001-01-01T00:00:00.000+02:00
     2001-01-01T00:00:00.000000001+02:00


来源:https://stackoverflow.com/questions/52619353/what-is-the-equivalent-format-string-of-datetimeformatter-iso-offset-date-time

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