Skip to content

Commit

Permalink
Correct upwards rounding of seconds by microsoft.sql.DateTimeOffset.v…
Browse files Browse the repository at this point in the history
…alueOf(OffsetDateTime)
  • Loading branch information
arashi01 committed Feb 26, 2024
1 parent 94152bc commit e675f92
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/main/java/microsoft/sql/DateTimeOffset.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
Expand Down
12 changes: 12 additions & 0 deletions src/test/java/microsoft/sql/DateTimeOffsetTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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()
);
}
}

0 comments on commit e675f92

Please sign in to comment.