Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a671baf

Browse files
Praful Makanisduskis
authored andcommitted
Fix Timestamp.parseTimestamp. (googleapis#4656)
* 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
1 parent 04206ac commit a671baf

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/Timestamp.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
import org.threeten.bp.LocalDateTime;
2828
import org.threeten.bp.ZoneOffset;
2929
import org.threeten.bp.format.DateTimeFormatter;
30+
import org.threeten.bp.format.DateTimeFormatterBuilder;
31+
import org.threeten.bp.temporal.TemporalAccessor;
3032

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

4850
private static final DateTimeFormatter format = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
4951

52+
private static final DateTimeFormatter timestampParser =
53+
new DateTimeFormatterBuilder()
54+
.appendOptional(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
55+
.optionalStart()
56+
.appendOffsetId()
57+
.optionalEnd()
58+
.toFormatter()
59+
.withZone(ZoneOffset.UTC);
60+
5061
private final long seconds;
5162
private final int nanos;
5263

@@ -170,7 +181,8 @@ public com.google.protobuf.Timestamp toProto() {
170181
* the timezone offset (always ends in "Z").
171182
*/
172183
public static Timestamp parseTimestamp(String timestamp) {
173-
Instant instant = Instant.parse(timestamp);
184+
TemporalAccessor temporalAccessor = timestampParser.parse(timestamp);
185+
Instant instant = Instant.from(temporalAccessor);
174186
return ofTimeSecondsAndNanos(instant.getEpochSecond(), instant.getNano());
175187
}
176188

google-cloud-clients/google-cloud-core/src/test/java/com/google/cloud/TimestampTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,15 @@ public void parseTimestamp() {
185185
.isEqualTo(Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 0));
186186
}
187187

188+
@Test
189+
public void parseTimestampWithoutTimeZoneOffset() {
190+
assertThat(Timestamp.parseTimestamp("0001-01-01T00:00:00")).isEqualTo(Timestamp.MIN_VALUE);
191+
assertThat(Timestamp.parseTimestamp("9999-12-31T23:59:59.999999999"))
192+
.isEqualTo(Timestamp.MAX_VALUE);
193+
assertThat(Timestamp.parseTimestamp("2015-10-12T15:14:54"))
194+
.isEqualTo(Timestamp.ofTimeSecondsAndNanos(TEST_TIME_SECONDS, 0));
195+
}
196+
188197
@Test
189198
public void fromProto() {
190199
com.google.protobuf.Timestamp proto =

0 commit comments

Comments
 (0)