Merge pull request #16319 from Michaelin007/proto
Convert Google Protocol Buffer Timestamp to LocalDate
This commit is contained in:
commit
2fca380422
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.protobuftimestamptolocaldate;
|
||||
|
||||
import com.google.protobuf.Timestamp;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class TimestampInstance {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(TimestampInstance.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
Instant currentTimestamp = Instant.now();
|
||||
Timestamp timestamp = Timestamp.newBuilder()
|
||||
.setSeconds(currentTimestamp.getEpochSecond())
|
||||
.setNanos(currentTimestamp.getNano())
|
||||
.build();
|
||||
logger.info(timestamp.toString());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.protobuftimestamptolocaldate;
|
||||
|
||||
import com.google.protobuf.Timestamp;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
|
||||
public class TimestampToLocalDate {
|
||||
|
||||
public static LocalDate convertToLocalDate(Timestamp timestamp) {
|
||||
Instant instant = Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());
|
||||
LocalDate time = instant.atZone(ZoneId.of("America/Montreal"))
|
||||
.toLocalDate();
|
||||
return time;
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.protobuftimestamptolocaldate;
|
||||
|
||||
import com.google.protobuf.Timestamp;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TimestampToLocalDateUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTimestamp_whenConvertedToLocalDate_thenSuccess() {
|
||||
Timestamp timestamp = Timestamp.newBuilder()
|
||||
.setSeconds(1000000000)
|
||||
.setNanos(778866000)
|
||||
.build();
|
||||
LocalDate time = TimestampToLocalDate.convertToLocalDate(timestamp);
|
||||
assertEquals(LocalDate.of(2001, 9, 8), time);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue