Skip to content

Commit

Permalink
Fix Timestamp.parseTimestamp. (#4656)
Browse files Browse the repository at this point in the history
* Fix parseTimestamp docs

* Fix timestamp without timezone offset

* Fix test cases related to timestamp.parseTimestamp

* added test case

* Fix timestampParser and added ZoneOffset in timestampParser
  • Loading branch information
Praful Makani authored and sduskis committed Mar 10, 2019
1 parent 04206ac commit a671baf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.format.DateTimeFormatterBuilder;
import org.threeten.bp.temporal.TemporalAccessor;

/**
* Represents a timestamp with nanosecond precision. Timestamps cover the range [0001-01-01,
Expand All @@ -47,6 +49,15 @@ public final class Timestamp implements Comparable<Timestamp>, Serializable {

private static final DateTimeFormatter format = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

private static final DateTimeFormatter timestampParser =
new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.optionalStart()
.appendOffsetId()
.optionalEnd()
.toFormatter()
.withZone(ZoneOffset.UTC);

private final long seconds;
private final int nanos;

Expand Down Expand Up @@ -170,7 +181,8 @@ public com.google.protobuf.Timestamp toProto() {
* the timezone offset (always ends in "Z").
*/
public static Timestamp parseTimestamp(String timestamp) {
Instant instant = Instant.parse(timestamp);
TemporalAccessor temporalAccessor = timestampParser.parse(timestamp);
Instant instant = Instant.from(temporalAccessor);
return ofTimeSecondsAndNanos(instant.getEpochSecond(), instant.getNano());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,15 @@ public void parseTimestamp() {
.isEqualTo(Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 0));
}

@Test
public void parseTimestampWithoutTimeZoneOffset() {
assertThat(Timestamp.parseTimestamp("0001-01-01T00:00:00")).isEqualTo(Timestamp.MIN_VALUE);
assertThat(Timestamp.parseTimestamp("9999-12-31T23:59:59.999999999"))
.isEqualTo(Timestamp.MAX_VALUE);
assertThat(Timestamp.parseTimestamp("2015-10-12T15:14:54"))
.isEqualTo(Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 0));
}

@Test
public void fromProto() {
com.google.protobuf.Timestamp proto =
Expand Down

0 comments on commit a671baf

Please sign in to comment.