1

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.

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

6 Comments

Would it be more about updating this.product to update properties importDate and/or expireDate to be ISO date strings? new Date() may not reflect the date of those objects values.
you can call toISOString on those date objects. the code here is just a sample.
Why not actually make the answer specific to their question and usage? Why just a an arbitrary sample? It could help them resolve their issue more effectively.
cuz the question doesn't give the data to deal with
Which Data do you need?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.