使用 Angular 发送类型日期时出现问题

Problem sending the type date with Angular

当我将日期从 Angular 添加到 Spring 时,Spring 保存前一天而不是我插入的日期。 当我尝试邮递员时一切正常所以问题是 Angular 发送数据。 我在 Spring 模型上的代码是:

  @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        private LocalDate importDate;
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        private LocalDate expireDate;

在我的控制器中:

@PostMapping("/addProduct")
        public ResponseEntity<Response> saveProduct(@RequestBody @Valid Product product) throws BadRequestException {
            log.info("Product to String: " + product);
            return ResponseEntity.ok(Response.builder()
                    .timeStamp(now())
                    .data(Map.of("product", productService.addProduct(product)))
                    .message("product added")
                    .status(CREATED)
                    .statusCode(CREATED.value())
                    .build()
            );
        }

在我的 component.html:

 <p-calendar appendTo="body" id="importDate" [(ngModel)]="product.importDate" placeholder={{product.importDate}} dateFormat="yy-mm-dd"></p-calendar>

In my components ts:
this.service.saveData(this.product).subscribe({
        next: (v) => this.toastMessage(v.status,v.message),
      error: (e) => this.errorMessage(e.error.message),
      complete: ()=> this.service.getData().subscribe(data=>{this.products=data})
      });

实在想不通,谢谢大佬们的回复

因为您期望后端的 iso 字符串中的日期在 javascript 将日期转换为字符串时不是默认的。你可以为此使用 toISOString() 方法。

new Date().toISOString()

以上只是一个例子。 toISOString 可以在任何日期对象上调用。

首先将日期更正为当地时区。
'Z' 附加到 date 以获得正确的本地时区值。

const localDate = date + 'Z';
const dateISO = new Date(localDate).toISOString().substring(0, 10);