Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the error when calling Timestamp.of(Date date) when date is pre epoch #3434

Merged
merged 2 commits into from
Jul 10, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -81,6 +81,10 @@ public static Timestamp ofTimeMicroseconds(long microseconds) {
long seconds = TimeUnit.MICROSECONDS.toSeconds(microseconds);
int nanos =
(int) TimeUnit.MICROSECONDS.toNanos(microseconds - TimeUnit.SECONDS.toMicros(seconds));
if (nanos < 0) {

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

seconds--;
nanos += TimeUnit.SECONDS.toNanos(1);
}
checkArgument(
Timestamps.isValid(seconds, nanos), "timestamp out of range: %s, %s", seconds, nanos);
return new Timestamp(seconds, nanos);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ public class TimestampTest {
private static final long TEST_TIME_MICROSECONDS = 10000100L;
private static final long TEST_TIME_MILLISECONDS =
TimeUnit.SECONDS.toMillis(1444662894L) + TimeUnit.MICROSECONDS.toMillis(1234);
private static final long TEST_TIME_MILLISECONDS_NEGATIVE = -1L;
private static final Date TEST_DATE = new Date(TEST_TIME_MILLISECONDS);
private static final Date TEST_DATE_PRE_EPOCH = new Date(TEST_TIME_MILLISECONDS_NEGATIVE);

@Rule public ExpectedException expectedException = ExpectedException.none();

Expand Down Expand Up @@ -80,6 +82,17 @@ public void ofDate() {
assertThat(timestamp.getNanos()).isEqualTo(expectedNanos);
}

@Test
public void ofDatePreEpoch() {
Timestamp timestamp = Timestamp.of(TEST_DATE_PRE_EPOCH);
Long expectedSeconds = TimeUnit.MILLISECONDS.toSeconds(TEST_TIME_MILLISECONDS_NEGATIVE) - 1;
Long expectedNanos =
TimeUnit.MILLISECONDS.toNanos(TEST_TIME_MILLISECONDS_NEGATIVE)
- TimeUnit.SECONDS.toNanos(expectedSeconds);
assertThat(timestamp.getSeconds()).isEqualTo(expectedSeconds);
assertThat(timestamp.getNanos()).isEqualTo(expectedNanos);
}

@Test
public void toDate() {
Timestamp timestamp = Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 1234 * 1000);
Expand Down