Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
Although it might look strange, this behaviour is - kinda - documented. But it's not so straighforward to figure out. In ZonedDateTime::toString docs it says: The format consists of the LocalDa...
#2: Post edited
- Although it might look strange, this behaviour is - *kinda* - documented. But it's not so straighforward to figure out.
- In [`ZonedDateTime::toString` docs](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/ZonedDateTime.html#toString()) it says:
- > The format consists of the `LocalDateTime` followed by the `ZoneOffset`.
- Therefore, we must check the [docs for `LocalDateTime::toString`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/LocalDateTime.html#toString()), which says:
- > 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.**
- The last sentence (which I highlighted above) is the key to understand it. If the seconds are omitted, it means that all the following fields (in this case, seconds and fractions of second) are zero.
- You didn't mention the Java version you're using, so I'll use mine (JDK 21) as an example. Look at the [source code for `ZonedDateTime::toString` method](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/time/ZonedDateTime.java#L2218):
- ```java
- public String toString() {
- String str = dateTime.toString() + offset.toString();
- if (offset != zone) {
- str += '[' + zone.toString() + ']';
- }
- return str;
- }
- ```
- It delegates to `dateTime.toString()` to build the date/time part. And the `dateTime` field is an instance of `LocalDateTime`, so let's see [its `toString` method](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/time/LocalDateTime.java#L1967):
- ```java
- public String toString() {
- return date.toString() + 'T' + time.toString();
- }
- ```
- It delegates the time part to its `time` field, which is a `LocalTime`, so let's see [its `toString` method](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/time/LocalTime.java#L1631):
- ```java
- public String toString() {
- StringBuilder buf = new StringBuilder(18);
- int hourValue = hour;
- int minuteValue = minute;
- int secondValue = second;
- int nanoValue = nano;
- buf.append(hourValue < 10 ? "0" : "").append(hourValue)
- .append(minuteValue < 10 ? ":0" : ":").append(minuteValue);
- if (secondValue > 0 || nanoValue > 0) {
- buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);
- if (nanoValue > 0) {
- buf.append('.');
- if (nanoValue % 1000_000 == 0) {
- buf.append(Integer.toString((nanoValue / 1000_000) + 1000).substring(1));
- } else if (nanoValue % 1000 == 0) {
- buf.append(Integer.toString((nanoValue / 1000) + 1000_000).substring(1));
- } else {
- buf.append(Integer.toString((nanoValue) + 1000_000_000).substring(1));
- }
- }
- }
- return buf.toString();
- }
- ```
- Finally we can see the reason: `if (secondValue > 0 || nanoValue > 0)` means that the output will stop at the minutes if both seconds and fractions of second are zero.
- ---
- # If you want to always print the seconds
- Then use a [`java.time.format.DateTimeFormatter`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/format/DateTimeFormatter.html):
- ```java
- DateTimeFormatter fmt = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX'['VV']'");
- System.out.println(fmt.format(recreated)); // 2000-01-01T23:00:00+11:00[Australia/Melbourne]
- ```
- But in this case, it'll always omit the fractions of second. To omit them only if they are zero, use a [`java.time.format.DateTimeFormatterBuilder`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/format/DateTimeFormatterBuilder.html). See the difference:
- ```java
- // fractions of second is zero
- ZonedDateTime zdt = Instant.parse("2000-01-01T12:00:01Z").atZone(ZoneId.of("Australia/Melbourne"));
- // formatter without fractions of second
- DateTimeFormatter noFractionFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX'['VV']'");
- // formatter with fractions of second, if not zero
- DateTimeFormatter fractionFormat = new DateTimeFormatterBuilder()
- .appendPattern("uuuu-MM-dd'T'HH:mm:ss")
- .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
- .appendPattern("XXX'['VV']'")
- .toFormatter();
- // none print fractions of second (as the value is zero)
- System.out.println(noFractionFormat.format(zdt));
- System.out.println(fractionFormat.format(zdt));
- // fractions of second isn't zero
- zdt = zdt.plusNanos(1);
- // don't print fractions of second
- System.out.println(noFractionFormat.format(zdt));
- // print fractions of second
- System.out.println(fractionFormat.format(zdt));
- ```
- The second formatter will print the fractions of second if they're not zero. The first one will never print it. The output is:
```- 2000-01-01T23:00:01+11:00[Australia/Melbourne]
- 2000-01-01T23:00:01+11:00[Australia/Melbourne]
- 2000-01-01T23:00:01+11:00[Australia/Melbourne]
- 2000-01-01T23:00:01.000000001+11:00[Australia/Melbourne]
- ```
- Although it might look strange, this behaviour is - *kinda* - documented. But it's not so straighforward to figure out.
- In [`ZonedDateTime::toString` docs](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/ZonedDateTime.html#toString()) it says:
- > The format consists of the `LocalDateTime` followed by the `ZoneOffset`.
- Therefore, we must check the [docs for `LocalDateTime::toString`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/LocalDateTime.html#toString()), which says:
- > 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.**
- The last sentence (which I highlighted above) is the key to understand it. If the seconds are omitted, it means that all the following fields (in this case, seconds and fractions of second) are zero.
- You didn't mention the Java version you're using, so I'll use mine (JDK 21) as an example. Look at the [source code for `ZonedDateTime::toString` method](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/time/ZonedDateTime.java#L2218):
- ```java
- public String toString() {
- String str = dateTime.toString() + offset.toString();
- if (offset != zone) {
- str += '[' + zone.toString() + ']';
- }
- return str;
- }
- ```
- It delegates to `dateTime.toString()` to build the date/time part. And the `dateTime` field is an instance of `LocalDateTime`, so let's see [its `toString` method](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/time/LocalDateTime.java#L1967):
- ```java
- public String toString() {
- return date.toString() + 'T' + time.toString();
- }
- ```
- It delegates the time part to its `time` field, which is a `LocalTime`, so let's see [its `toString` method](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/time/LocalTime.java#L1631):
- ```java
- public String toString() {
- StringBuilder buf = new StringBuilder(18);
- int hourValue = hour;
- int minuteValue = minute;
- int secondValue = second;
- int nanoValue = nano;
- buf.append(hourValue < 10 ? "0" : "").append(hourValue)
- .append(minuteValue < 10 ? ":0" : ":").append(minuteValue);
- if (secondValue > 0 || nanoValue > 0) {
- buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);
- if (nanoValue > 0) {
- buf.append('.');
- if (nanoValue % 1000_000 == 0) {
- buf.append(Integer.toString((nanoValue / 1000_000) + 1000).substring(1));
- } else if (nanoValue % 1000 == 0) {
- buf.append(Integer.toString((nanoValue / 1000) + 1000_000).substring(1));
- } else {
- buf.append(Integer.toString((nanoValue) + 1000_000_000).substring(1));
- }
- }
- }
- return buf.toString();
- }
- ```
- Finally we can see the reason: `if (secondValue > 0 || nanoValue > 0)` means that the output will stop at the minutes if both seconds and fractions of second are zero.
- ---
- # If you want to always print the seconds
- Then use a [`java.time.format.DateTimeFormatter`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/format/DateTimeFormatter.html):
- ```java
- DateTimeFormatter fmt = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX'['VV']'");
- System.out.println(fmt.format(recreated)); // 2000-01-01T23:00:00+11:00[Australia/Melbourne]
- ```
- But in this case, it'll always omit the fractions of second. To omit them only if they are zero, use a [`java.time.format.DateTimeFormatterBuilder`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/format/DateTimeFormatterBuilder.html). See the difference:
- ```java
- // fractions of second is zero
- ZonedDateTime zdt = Instant.parse("2000-01-01T12:00:01Z").atZone(ZoneId.of("Australia/Melbourne"));
- // formatter without fractions of second
- DateTimeFormatter noFractionFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX'['VV']'");
- // formatter with fractions of second, if not zero
- DateTimeFormatter fractionFormat = new DateTimeFormatterBuilder()
- .appendPattern("uuuu-MM-dd'T'HH:mm:ss")
- .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
- .appendPattern("XXX'['VV']'")
- .toFormatter();
- // none print fractions of second (as the value is zero)
- System.out.println(noFractionFormat.format(zdt));
- System.out.println(fractionFormat.format(zdt));
- // fractions of second isn't zero
- zdt = zdt.plusNanos(1);
- // don't print fractions of second
- System.out.println(noFractionFormat.format(zdt));
- // print fractions of second
- System.out.println(fractionFormat.format(zdt));
- ```
- The second formatter will print the fractions of second if they're not zero. The first one will never print it. The output is:
- ```none
- 2000-01-01T23:00:01+11:00[Australia/Melbourne]
- 2000-01-01T23:00:01+11:00[Australia/Melbourne]
- 2000-01-01T23:00:01+11:00[Australia/Melbourne]
- 2000-01-01T23:00:01.000000001+11:00[Australia/Melbourne]
- ```
#1: Initial revision
Although it might look strange, this behaviour is - *kinda* - documented. But it's not so straighforward to figure out.
In [`ZonedDateTime::toString` docs](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/ZonedDateTime.html#toString()) it says:
> The format consists of the `LocalDateTime` followed by the `ZoneOffset`.
Therefore, we must check the [docs for `LocalDateTime::toString`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/LocalDateTime.html#toString()), which says:
> 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.**
The last sentence (which I highlighted above) is the key to understand it. If the seconds are omitted, it means that all the following fields (in this case, seconds and fractions of second) are zero.
You didn't mention the Java version you're using, so I'll use mine (JDK 21) as an example. Look at the [source code for `ZonedDateTime::toString` method](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/time/ZonedDateTime.java#L2218):
```java
public String toString() {
String str = dateTime.toString() + offset.toString();
if (offset != zone) {
str += '[' + zone.toString() + ']';
}
return str;
}
```
It delegates to `dateTime.toString()` to build the date/time part. And the `dateTime` field is an instance of `LocalDateTime`, so let's see [its `toString` method](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/time/LocalDateTime.java#L1967):
```java
public String toString() {
return date.toString() + 'T' + time.toString();
}
```
It delegates the time part to its `time` field, which is a `LocalTime`, so let's see [its `toString` method](https://github.com/openjdk/jdk21u/blob/master/src/java.base/share/classes/java/time/LocalTime.java#L1631):
```java
public String toString() {
StringBuilder buf = new StringBuilder(18);
int hourValue = hour;
int minuteValue = minute;
int secondValue = second;
int nanoValue = nano;
buf.append(hourValue < 10 ? "0" : "").append(hourValue)
.append(minuteValue < 10 ? ":0" : ":").append(minuteValue);
if (secondValue > 0 || nanoValue > 0) {
buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);
if (nanoValue > 0) {
buf.append('.');
if (nanoValue % 1000_000 == 0) {
buf.append(Integer.toString((nanoValue / 1000_000) + 1000).substring(1));
} else if (nanoValue % 1000 == 0) {
buf.append(Integer.toString((nanoValue / 1000) + 1000_000).substring(1));
} else {
buf.append(Integer.toString((nanoValue) + 1000_000_000).substring(1));
}
}
}
return buf.toString();
}
```
Finally we can see the reason: `if (secondValue > 0 || nanoValue > 0)` means that the output will stop at the minutes if both seconds and fractions of second are zero.
---
# If you want to always print the seconds
Then use a [`java.time.format.DateTimeFormatter`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/format/DateTimeFormatter.html):
```java
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX'['VV']'");
System.out.println(fmt.format(recreated)); // 2000-01-01T23:00:00+11:00[Australia/Melbourne]
```
But in this case, it'll always omit the fractions of second. To omit them only if they are zero, use a [`java.time.format.DateTimeFormatterBuilder`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/time/format/DateTimeFormatterBuilder.html). See the difference:
```java
// fractions of second is zero
ZonedDateTime zdt = Instant.parse("2000-01-01T12:00:01Z").atZone(ZoneId.of("Australia/Melbourne"));
// formatter without fractions of second
DateTimeFormatter noFractionFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX'['VV']'");
// formatter with fractions of second, if not zero
DateTimeFormatter fractionFormat = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-dd'T'HH:mm:ss")
.appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
.appendPattern("XXX'['VV']'")
.toFormatter();
// none print fractions of second (as the value is zero)
System.out.println(noFractionFormat.format(zdt));
System.out.println(fractionFormat.format(zdt));
// fractions of second isn't zero
zdt = zdt.plusNanos(1);
// don't print fractions of second
System.out.println(noFractionFormat.format(zdt));
// print fractions of second
System.out.println(fractionFormat.format(zdt));
```
The second formatter will print the fractions of second if they're not zero. The first one will never print it. The output is:
```
2000-01-01T23:00:01+11:00[Australia/Melbourne]
2000-01-01T23:00:01+11:00[Australia/Melbourne]
2000-01-01T23:00:01+11:00[Australia/Melbourne]
2000-01-01T23:00:01.000000001+11:00[Australia/Melbourne]
```
