Skip to content

Commit

Permalink
Adding Timestamp.toDate() (#3313)
Browse files Browse the repository at this point in the history
  • Loading branch information
schmidt-sebastian authored May 25, 2018
1 parent 5c4c5bc commit a83f9ed
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,18 @@ public java.sql.Timestamp toSqlTimestamp() {
return ts;
}

/**
* Returns a new {@code java.util.Date} corresponding to this {@code timestamp}. Any
* sub-millisecond precision will be stripped.
*
* @return An approximate {@code java.util.Date} representation of this {@code timestamp}.
*/
public Date toDate() {
long secondsInMilliseconds = TimeUnit.SECONDS.toMillis(this.seconds);
long nanosInMilliseconds = TimeUnit.NANOSECONDS.toMillis(this.nanos);
return new Date(secondsInMilliseconds + nanosInMilliseconds);
}

@Override
public int compareTo(Timestamp other) {
int r = Long.compare(seconds, other.seconds);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@

import com.google.common.testing.EqualsTester;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
Expand All @@ -35,6 +37,9 @@ public class TimestampTest {
private static final String TEST_TIME_ISO = "2015-10-12T15:14:54Z";
private static final long TEST_TIME_SECONDS = 1444662894L;
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 Date TEST_DATE = new Date(TEST_TIME_MILLISECONDS);

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

Expand Down Expand Up @@ -64,6 +69,24 @@ public void ofMicroseconds() {
assertThat(timestamp.getNanos()).isEqualTo(TEST_TIME_MICROSECONDS % 1000000L * 1000);
}

@Test
public void ofDate() {
Timestamp timestamp = Timestamp.of(TEST_DATE);
Long expectedSeconds = TimeUnit.MILLISECONDS.toSeconds(TEST_TIME_MILLISECONDS);
Long expectedNanos =
TimeUnit.MILLISECONDS.toNanos(TEST_TIME_MILLISECONDS)
- 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);
Date date = timestamp.toDate();
assertThat(TEST_TIME_MILLISECONDS).isEqualTo(date.getTime());
}

@Test
public void toFromSqlTimestamp() {
long seconds = TEST_TIME_SECONDS;
Expand Down

0 comments on commit a83f9ed

Please sign in to comment.