简体   繁体   English

如何在 Java 中将日期类型 Angular 转换为 LocalDate

[英]How to convert Date type Angular to LocalDate in Java

I have a frontend part in Angular 7 and a backend part in Java with Spring Boot framework.我在 Angular 7 中有一个前端部分,在 Java 中有一个带有 Spring Boot 框架的后端部分。 I want to post to my backend a Date object.我想向我的后端发布一个 Date 对象。 In backend I have a Local Date object.在后端,我有一个本地日期对象。 I don't need LocalDateTime object我不需要 LocalDateTime 对象

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] .wsmsDefaultHandlerExceptionResolver : 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; 2019-08-06 08:21:02.185 WARN 1444 --- [nio-8080-exec-4] .wsmsDefaultHandlerExceptionResolver :已解决 [org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:无法反序列化类型java.time.LocalDatejava.time.LocalDate from String "2019-08-06T00:00:00.000+0000": 无法反序列化 java.time.LocalDate: (java.time.format.DateTimeParseException) Text '2019-08-06T00:00:00.000+0000 ' 无法解析,在索引 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嵌套的例外是com.fasterxml.jackson.databind.exc.InvalidFormatException:不能类型的反序列化值java.time.LocalDate从字符串“2019-08-06T00:00:00.000 + 0000”:无法反序列化java.time.LocalDate: (java.time.format.DateTimeParseException) 无法解析文本“2019-08-06T00:00:00.000+0000”,在索引 23 处找到未解析的文本

How to send LocalDate and LocalDateTime from Angular to Spring如何将 LocalDate 和 LocalDateTime 从 Angular 发送到 Spring

nicer solution:更好的解决方案:

app.module.ts app.module.ts

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

app.service.ts应用服务.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.如果您只想转换 LocalDate,您可以离开 datePipe 并从 Angular 发送 new Date().toISOString() 。 But since the Questioner especially asked for LocalDate you need some sort of Format to get this kind of Date -> "yyyy-MM-dd" .但是由于提问者特别要求 LocalDate 你需要某种格式来获得这种 Date -> "yyyy-MM-dd" 。 Only with this Spring is able to do its magic.只有有了这个 Spring 才能发挥它的魔力。

Btw.顺便提一句。 same is possivle if you just need the time (HH:mm:ss.SSSXXX) which is DateTimeFormat.ISO.TIME .如果您只需要 DateTimeFormat.ISO.TIME 的时间 (HH:mm:ss.SSSXXX),同样是可能的。

finish!结束!

not so nice solution and more uncomfortable -> convert to String ( not tested since i was happy with Spring solution)不是很好的解决方案,更不舒服-> 转换为字符串未测试,因为我对 Spring 解决方案很满意)

app.service.ts应用服务.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...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM