Home > Software engineering >  Problem sending the type date with Angular
Problem sending the type date with Angular

Time:02-19

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.

CodePudding user response:

Because you are expecting date in iso string at backend which is not default when javascript converts date to string. you can use toISOString() method for this.

new Date().toISOString()

the above is just an example. toISOString can be called on any date object.

CodePudding user response:

First correct the date to local timezone.
Add Z in the end for getting the correct value with local timezone

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