如何将 grpc java proto "timestamp" 转换为日期?

How to convert grpc java proto "timestamp" to date?

request.getProductexpirationdate() 中的错误,因为它不是原型中指定为“时间戳”的“日期”。

实体 class 有一个“日期”但原型没有“日期”只有“时间戳”所以它不兼容。

如何将时间戳转换为日期以使其兼容并将数据格式发送为日期?

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

假设您指的是 google.protobuf.Timestamp,最简单的转换方法是使用 com.google.protobuf.util.Timestamps utility:

Timestamp timestamp = Timestamp.fromMillis(date.getTime());

Timestamp 将日期存储为自 1970 年以来的秒和纳秒,而 Date 存储自 1970 年以来的毫秒。如果您查阅 google.protobuf.Timestamp documentation,它提到了如何手动转换:

// 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();