Skip to content

Commit e675f92

Browse files
committed
Correct upwards rounding of seconds by microsoft.sql.DateTimeOffset.valueOf(OffsetDateTime)
1 parent 94152bc commit e675f92

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

src/main/java/microsoft/sql/DateTimeOffset.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,11 @@ private DateTimeOffset(java.sql.Timestamp timestamp, int minutesOffset) {
7878
* @param offsetDateTime A java.time.OffsetDateTime value
7979
* @apiNote DateTimeOffset represents values to 100ns precision. If the java.time.OffsetDateTime instance represents
8080
* a value that is more precise, values in excess of the 100ns precision are rounded to the nearest
81-
* multiple of 100ns.
81+
* multiple of 100ns. Values within 50 nanoseconds of the next second are rounded up to the next second.
8282
*/
8383
private DateTimeOffset(java.time.OffsetDateTime offsetDateTime) {
8484
int hundredNanos = ((offsetDateTime.getNano() + 50) / 100);
85-
this.utcMillis = offsetDateTime.toEpochSecond() * 1000;
85+
this.utcMillis = (offsetDateTime.toEpochSecond() * 1000) + (hundredNanos / HUNDRED_NANOS_PER_SECOND * 1000);
8686
this.nanos = 100 * (hundredNanos % HUNDRED_NANOS_PER_SECOND);
8787
this.minutesOffset = offsetDateTime.getOffset().getTotalSeconds() / 60;
8888
}
@@ -127,7 +127,7 @@ public static DateTimeOffset valueOf(java.sql.Timestamp timestamp, Calendar cale
127127
* @return The DateTimeOffset value of the input java.time.OffsetDateTime
128128
* @apiNote DateTimeOffset represents values to 100ns precision. If the java.time.OffsetDateTime instance represents
129129
* a value that is more precise, values in excess of the 100ns precision are rounded to the nearest
130-
* multiple of 100ns.
130+
* multiple of 100ns. Values within 50 nanoseconds of the next second are rounded up to the next second.
131131
*/
132132
public static DateTimeOffset valueOf(java.time.OffsetDateTime offsetDateTime) {
133133
return new DateTimeOffset(offsetDateTime);

src/test/java/microsoft/sql/DateTimeOffsetTest.java

+12
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,16 @@ void valueOfOffsetDateTime() {
3636
);
3737
}
3838

39+
@Test
40+
@DisplayName("DateTimeOffset.valueOf(offsetDateTime) correctly rounds up values within 50 nanoseconds of the next second.")
41+
void valueOfOffsetDateTimeRounding() {
42+
OffsetDateTime offsetDateTime = OffsetDateTime.now().withNano(999999950);
43+
Assertions
44+
.assertEquals(
45+
offsetDateTime
46+
.withSecond(offsetDateTime.getSecond() + 1)
47+
.withNano(0),
48+
DateTimeOffset.valueOf(offsetDateTime).getOffsetDateTime()
49+
);
50+
}
3951
}

0 commit comments

Comments
 (0)