'How to convert grpc java proto "timestamp" to date?
Error in request.getProductexpirationdate() since its not "Date" in proto thats specified as "timestamp".
Entity class has a "Date" but proto has no "Date" only "timestamp" so its not compatible.
How do i convert timestamp to date to make it compatible and sending data format as Date?
// EntityTest.class
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProductEntity {
private Integer purchase_item;
private String productname;
private String productbrand;
private Double productprice;
private String productdescription;
private Integer productquantity;
private Date productexpirationdate;
}
//GRPC Service
//Error in request.getProductexpirationdate() since its not "Date"
@GrpcService
public class ProductGRPCserver extends ProductServiceImplBase{
@Autowired
private ProductServiceImpl productServiceImpl;
@Autowired
private ProductDAO productDAO;
@Override
public void insert(Product request, StreamObserver<APIResponse> responseObserver) {
ProductEntity productEntity = new ProductEntity();
productEntity.setPurchase_item(request.getPurchaseItem());
productEntity.setProductname(request.getProductname());
productEntity.setProductbrand(request.getProductbrand());
productEntity.setProductprice(request.getProductprice());
productEntity.setProductdescription(request.getProductdescription());
productEntity.setProductquantity(request.getProductquantity());
productEntity.setProductexpirationdate(request.getProductexpirationdate());
productServiceImpl.saveDataFromDTO(productEntity);
APIResponse.Builder responce = APIResponse.newBuilder();
responce.setResponseCode(0).setResponsemessage("Succefull added to database " +productEntity);
responseObserver.onNext(responce.build());
responseObserver.onCompleted();
}
Solution 1:[1]
Assuming you are referring to google.protobuf.Timestamp
, the easiest way to convert is with the com.google.protobuf.util.Timestamps utility:
Timestamp timestamp = Timestamp.fromMillis(date.getTime());
Timestamp stores the date as seconds and nanoseconds since 1970 whereas Date stores milliseconds since 1970. If you consult the google.protobuf.Timestamp
documentation, it mentions how to do this manually conversion:
// The example used currentTimeMillis(), but let's use Date instead.
// long millis = System.currentTimeMillis();
long millis = date.getTime();
Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
.setNanos((int) ((millis % 1000) * 1000000)).build();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Eric Anderson |