1

I have a frontend part in Angular 7 and a backend part in Java with Spring Boot framework. I want to post to my backend a Date object. In backend I have a Local Date object. I don't need LocalDateTime object

my date service in angular. I need to preserve Date type and not use string.

addDate(): Observable<Date> {
    let now = new Date();
    return this.http
      .post<Date>('/api/date', now)
      .pipe(
        tap(response => {
          return response;
        }),
        catchError(error => this.notificationService.handleError(error))
      );
  }

my backend service :

    @PostMapping
    public LocalDate addIrregularity(@RequestBody LocalDate date, HttpServletRequest request) {
        log.info(date);
        return date;
    }

And i have this error:

2019-08-06 08:21:02.185 WARN 1444 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type java.time.LocalDate from String "2019-08-06T00:00:00.000+0000": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '2019-08-06T00:00:00.000+0000' could not be parsed, unparsed text found at index 23; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.time.LocalDate from String "2019-08-06T00:00:00.000+0000": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '2019-08-06T00:00:00.000+0000' could not be parsed, unparsed text found at index 23

Serenity
  • 35,289
  • 20
  • 120
  • 115
Cédric R
  • 33
  • 1
  • 6
  • 1
    You are sanding date with time(2019-08-06T00:00:00.000+0000) but parsing in `LocalDate` just date. – Muhammad Usman Aug 06 '19 at 08:28
  • `LocalDateTime` or maybe even `OffsetDateTime` should be used here... – deHaar Aug 06 '19 at 08:31
  • The exception message mentions index 23, that is where the offset, `+0000`, is. Just an uninformed guess, it may be that parsing expected the offset to be written with a colon between hours and minutes, `+00:00`. – Ole V.V. Aug 06 '19 at 14:36

1 Answers1

0

How to send LocalDate and LocalDateTime from Angular to Spring

nicer solution:

app.module.ts

import {DatePipe} from '@angular/common';
.
.
.
providers: [DatePipe]

app.service.ts

import { DatePipe } from '@angular/common';

 constructor( private datePipe: DatePipe) {}

public sendStuff():  Observable<any>{
    let params = new HttpParams().set("date", this.datePipe.transform(new Date(),"yyyy-MM-dd"))
    .set("datetime",new Date().toISOString());
    return this.http.post<any>("urlPath../values/show", "Body" , {
      headers: new HttpHeaders({
        'Accept': 'application/json'
      }),
      params
    }); 
  }

Spring Part

@PostMapping(path="values/show")
public Map<String, Object>  showValues(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)  LocalDate date,
 @RequestParam("datetime")  @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDateTime datetime) {) {
...
}

If you just want to convert LocalDate you can leave the datePipe away and just send new Date().toISOString() from Angular. But since the Questioner especially asked for LocalDate you need some sort of Format to get this kind of Date -> "yyyy-MM-dd" . Only with this Spring is able to do its magic.

Btw. same is possivle if you just need the time (HH:mm:ss.SSSXXX) which is DateTimeFormat.ISO.TIME .

finish!

not so nice solution and more uncomfortable -> convert to String (not tested since i was happy with Spring solution)

app.service.ts

public sendStuff():  Observable<any>{
    let params = new HttpParams().set("datetime",new Date().toLocaleString())
    .set("datetime",new Date().toISOString());
    return this.http.post<any>("urlPath../values/show", "Body" , {
      headers: new HttpHeaders({
        'Accept': 'application/json'
      }),
      params
    }); 
  }

Spring:

@PostMapping(path="values/show")
public Map<String, Object>  showValues( @RequestParam String date,  @RequestParam String datetime) {
...
     // code to transform String to Date copied somewhere
 //Create a DateTimeFormatter with your required format:
 DateTimeFormatter dateTimeFormat = new DateTimeFormatter(DateTimeFormatter.BASIC_ISO_DATE);

    //Next parse the date from the @RequestParam, specifying the TO type as a TemporalQuery:
   LocalDateTime date = dateTimeFormat.parse(datetime, LocalDateTime::from);

   // some more code to transform LocalDate...
}
dino
  • 183
  • 2
  • 8