Java 8 DateTimeFormatter在零时删除millis? [英] Java 8 DateTimeFormatter dropping millis when they're zero?
问题描述
这似乎很奇怪。 Java 8根据Millis是否为零来格式化输出格式。您如何强制Java 8(1.8.0_20)始终吐出毫厘,无论它们是否为零?
This seems weird. Java 8 is formatting the output differently depending on whether the millis is zero. How do you force Java 8 (1.8.0_20) to always spit out the millis regardless of if they're zero or not?
public static void main(String[] args) {
TemporalAccessor zeroedMillis = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse("2015-07-14T20:50:00.000Z");
TemporalAccessor hasMillis = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse("2015-07-14T20:50:00.333Z");
System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(zeroedMillis));
System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(hasMillis));
}
2015-07-14T20:50:00Z
2015-07-14T20:50:00.333Z
推荐答案
您基本上不使用 ISO_OFFSET_DATE_TIME
:
如果您遵循该文档,则会得到 ISO_LOCAL_TIME
的文档,该文档具有:
If you follow the documentation for that, you end up in the docs of ISO_LOCAL_TIME
which has:
这将返回一个不变的格式化程序,该格式化程序能够格式化和解析ISO-8601扩展的本地时间格式。格式包括:
This returns an immutable formatter capable of formatting and parsing the ISO-8601 extended local time format. The format consists of:
- 一天中的两位数字。前面会先加上零,以确保两位数字。
- 冒号
- 每小时的分钟数两位。预先填充零以确保两位数字。
- 如果分钟不可用,则表示格式已完成。
- 冒号
- 第二分钟为两位数。预先填充零以确保两位数字。
- 如果毫微秒为零或不可用,则表示格式已完成。
- 小数点
- 纳秒级的一位到九位数字。将根据需要输出尽可能多的数字。
- Two digits for the hour-of-day. This is pre-padded by zero to ensure two digits.
- A colon
- Two digits for the minute-of-hour. This is pre-padded by zero to ensure two digits.
- If the second-of-minute is not available then the format is complete.
- A colon
- Two digits for the second-of-minute. This is pre-padded by zero to ensure two digits.
- If the nano-of-second is zero or not available then the format is complete.
- A decimal point
- One to nine digits for the nano-of-second. As many digits will be output as required.
如果您始终只希望3位数字,我怀疑您想要 DateTimeFormatter.ofPattern
,其格式为 yyyy-MM-dd'T'HH:mm:ss.SSSX
。
If you always want exactly 3 digits, I suspect you want DateTimeFormatter.ofPattern
with a pattern of yyyy-MM-dd'T'HH:mm:ss.SSSX
.
这篇关于Java 8 DateTimeFormatter在零时删除millis?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!