Skip to content
Advertisement

Problem sending the type date with Angular

When I add the date to Spring from Angular, Spring save the day before instead the date that I insert. When I tried on postman everything works so the problem is when Angular send the data. My code on Spring model is:

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

in my controller:

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

In my 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})
      });

I really can’t figure out why, thanks a lot who gonna reply me.

Advertisement

Answer

First correct the date to local timezone.
Append 'Z' to date for getting the correct value with local timezone.

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