Skip to content

Commit b3f3df6

Browse files
committed
Fixed timestamp creation
1 parent c50dde5 commit b3f3df6

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

table/src/main/java/tech/ydb/table/values/PrimitiveValue.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,14 +291,18 @@ public static PrimitiveValue newDatetime(LocalDateTime value) {
291291

292292
public static PrimitiveValue newTimestamp(long microsSinceEpoch) {
293293
if (microsSinceEpoch < 0) {
294-
throw new IllegalArgumentException("negative microsSinceEpoch: " + microsSinceEpoch);
294+
throw new IllegalArgumentException("Negative microsSinceEpoch: " + microsSinceEpoch);
295295
}
296296
return new InstantValue(PrimitiveType.Timestamp, microsSinceEpoch);
297297
}
298298

299299
public static PrimitiveValue newTimestamp(Instant value) {
300-
long micros = TimeUnit.SECONDS.toMicros(value.getEpochSecond()) +
301-
TimeUnit.NANOSECONDS.toMicros(value.getNano());
300+
long seconds = value.getEpochSecond();
301+
if (seconds < 0) {
302+
throw new IllegalArgumentException("Instant before epoch: " + value);
303+
}
304+
int nanos = value.getNano();
305+
long micros = seconds * 1000000L + nanos / 1000;
302306
return new InstantValue(PrimitiveType.Timestamp, micros);
303307
}
304308

table/src/test/java/tech/ydb/table/types/PrimitiveTypeTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ public class PrimitiveTypeTest {
1717
@Test
1818
public void timestampTest() {
1919
PrimitiveValue min = PrimitiveValue.newTimestamp(Instant.EPOCH);
20+
Assert.assertEquals(min, PrimitiveValue.newTimestamp(0));
2021
Value minValue = min.toPb();
2122

2223
Assert.assertEquals(0, minValue.getUint32Value());
@@ -27,6 +28,7 @@ public void timestampTest() {
2728
Assert.assertEquals(0, minValue.getHigh128());
2829

2930
PrimitiveValue max = PrimitiveValue.newTimestamp(Instant.parse("2105-12-31T23:59:59.999999Z"));
31+
Assert.assertEquals(max, PrimitiveValue.newTimestamp(4291747199999999l));
3032
Value maxValue = max.toPb();
3133

3234
Assert.assertEquals(0, maxValue.getUint32Value());
@@ -35,5 +37,15 @@ public void timestampTest() {
3537
Assert.assertEquals(0, maxValue.getInt64Value());
3638
Assert.assertEquals(0, maxValue.getLow128());
3739
Assert.assertEquals(0, maxValue.getHigh128());
40+
41+
IllegalArgumentException err1 = Assert.assertThrows(
42+
IllegalArgumentException.class, () -> PrimitiveValue.newTimestamp(-1)
43+
);
44+
Assert.assertEquals("Negative microsSinceEpoch: -1", err1.getMessage());
45+
46+
IllegalArgumentException err2 = Assert.assertThrows(
47+
IllegalArgumentException.class, () -> PrimitiveValue.newTimestamp(Instant.EPOCH.minusNanos(1))
48+
);
49+
Assert.assertEquals("Instant before epoch: 1969-12-31T23:59:59.999999999Z", err2.getMessage());
3850
}
3951
}

0 commit comments

Comments
 (0)