diff --git a/src/main/java/microsoft/sql/DateTimeOffset.java b/src/main/java/microsoft/sql/DateTimeOffset.java index 49fe0a85e..88be23b60 100644 --- a/src/main/java/microsoft/sql/DateTimeOffset.java +++ b/src/main/java/microsoft/sql/DateTimeOffset.java @@ -78,11 +78,11 @@ private DateTimeOffset(java.sql.Timestamp timestamp, int minutesOffset) { * @param offsetDateTime A java.time.OffsetDateTime value * @apiNote DateTimeOffset represents values to 100ns precision. If the java.time.OffsetDateTime instance represents * a value that is more precise, values in excess of the 100ns precision are rounded to the nearest - * multiple of 100ns. + * multiple of 100ns. Values within 50 nanoseconds of the next second are rounded up to the next second. */ private DateTimeOffset(java.time.OffsetDateTime offsetDateTime) { int hundredNanos = ((offsetDateTime.getNano() + 50) / 100); - this.utcMillis = offsetDateTime.toEpochSecond() * 1000; + this.utcMillis = (offsetDateTime.toEpochSecond() * 1000) + (hundredNanos / HUNDRED_NANOS_PER_SECOND * 1000); this.nanos = 100 * (hundredNanos % HUNDRED_NANOS_PER_SECOND); this.minutesOffset = offsetDateTime.getOffset().getTotalSeconds() / 60; } @@ -127,7 +127,7 @@ public static DateTimeOffset valueOf(java.sql.Timestamp timestamp, Calendar cale * @return The DateTimeOffset value of the input java.time.OffsetDateTime * @apiNote DateTimeOffset represents values to 100ns precision. If the java.time.OffsetDateTime instance represents * a value that is more precise, values in excess of the 100ns precision are rounded to the nearest - * multiple of 100ns. + * multiple of 100ns. Values within 50 nanoseconds of the next second are rounded up to the next second. */ public static DateTimeOffset valueOf(java.time.OffsetDateTime offsetDateTime) { return new DateTimeOffset(offsetDateTime); diff --git a/src/test/java/microsoft/sql/DateTimeOffsetTest.java b/src/test/java/microsoft/sql/DateTimeOffsetTest.java index 9237bbfc3..10477a083 100644 --- a/src/test/java/microsoft/sql/DateTimeOffsetTest.java +++ b/src/test/java/microsoft/sql/DateTimeOffsetTest.java @@ -36,4 +36,16 @@ void valueOfOffsetDateTime() { ); } + @Test + @DisplayName("DateTimeOffset.valueOf(offsetDateTime) correctly rounds up values within 50 nanoseconds of the next second.") + void valueOfOffsetDateTimeRounding() { + OffsetDateTime offsetDateTime = OffsetDateTime.now().withNano(999999950); + Assertions + .assertEquals( + offsetDateTime + .withSecond(offsetDateTime.getSecond() + 1) + .withNano(0), + DateTimeOffset.valueOf(offsetDateTime).getOffsetDateTime() + ); + } }