diff --git a/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/Timestamp.java b/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/Timestamp.java index 02bb98131366..618ef9c7211e 100644 --- a/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/Timestamp.java +++ b/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/Timestamp.java @@ -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, @@ -47,6 +49,15 @@ public final class Timestamp implements Comparable, 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; @@ -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()); } diff --git a/google-cloud-clients/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java b/google-cloud-clients/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java index 8a72abbee4e5..db9ede84dce1 100644 --- a/google-cloud-clients/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java +++ b/google-cloud-clients/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java @@ -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 =