Merge pull request #16319 from Michaelin007/proto

Convert Google Protocol Buffer Timestamp to LocalDate
This commit is contained in:
Maiklins 2024-04-11 23:53:04 +02:00 committed by GitHub
commit 2fca380422
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
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);
}
}