Java 8 DateTimeFormatter 在它们为零时下降毫秒?
Java 8 DateTimeFormatter dropping millis when they're zero?
这看起来很奇怪。 Java 8 根据毫秒是否为零来格式化输出。你如何强制 Java 8 (1.8.0_20) 总是吐出毫秒,不管它们是否为零?
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
的文档,其中包含:
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
。
这看起来很奇怪。 Java 8 根据毫秒是否为零来格式化输出。你如何强制 Java 8 (1.8.0_20) 总是吐出毫秒,不管它们是否为零?
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
的文档,其中包含:
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
。