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 Timestamp.parseTimestamp. #4656

Merged
merged 5 commits into from
Mar 10, 2019
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 @@ -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