Convert Google Protocol Buffer Timestamp to LocalDate

This commit is contained in:
michaelin007 2024-04-07 05:55:51 +00:00
parent 9e46a49f20
commit 783795b4ff
3 changed files with 62 additions and 0 deletions

View File

@ -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());
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}