Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ protected <T> T convertToType(final Class<T> targetType, final Object value) thr
// didn't include the milliseconds. The following code
// ensures it works consistently across JDK versions
final java.sql.Timestamp timestamp = (java.sql.Timestamp) value;
long timeInMillis = timestamp.getTime() / 1000 * 1000;
long timeInMillis = Math.floorDiv(timestamp.getTime(), 1000) * 1000;
timeInMillis += timestamp.getNanos() / 1000000;
return toDate(targetType, timeInMillis);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,14 @@

package org.apache.commons.beanutils2.converters;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

import org.junit.jupiter.api.Test;

/**
* Test Case for the DateConverter class.
*/
Expand Down Expand Up @@ -66,4 +71,29 @@ protected DateConverter makeConverter(final Date defaultValue) {
protected Date toType(final Calendar value) {
return value.getTime();
}

/**
* A pre-epoch {@link Timestamp} carries a non-negative sub-second part in {@code getNanos()}, so decomposing
* {@code getTime()} into whole seconds must floor: integer division truncates toward zero for negative values and
* gains a whole second.
*/
@Test
void testConvertPreEpochSqlTimestamp() {
// 1969-12-31T23:59:59.500Z: getTime() == -500, getNanos() == 500_000_000
final Timestamp timestamp = new Timestamp(-500L);
assertEquals(-500L, makeConverter().convert(getExpectedType(), timestamp).getTime());
}

/**
* For {@code getTime()} in {@code [Long.MIN_VALUE, Long.MIN_VALUE + 807]} the whole-second term
* {@code Math.floorDiv(getTime(), 1000) * 1000} wraps around {@link Long#MIN_VALUE}, but adding the non-negative
* {@code getNanos() / 1_000_000} wraps it back: the two terms reconstruct {@code getTime()} exactly in
* two's-complement arithmetic, so no overflow guard is needed.
*/
@Test
void testConvertExtremePreEpochSqlTimestamp() {
assertEquals(Long.MIN_VALUE, makeConverter().convert(getExpectedType(), new Timestamp(Long.MIN_VALUE)).getTime());
// last value whose whole-second term still wraps
assertEquals(Long.MIN_VALUE + 807, makeConverter().convert(getExpectedType(), new Timestamp(Long.MIN_VALUE + 807)).getTime());
}
}
Loading