首页 > 解决方案 > 如何在 Java 中将日期类型 Angular 转换为 LocalDate

问题描述

我在 Angular 7 中有一个前端部分,在 Java 中有一个带有 Spring Boot 框架的后端部分。我想向我的后端发布一个 Date 对象。在后端我有一个本地日期对象。我不需要 LocalDateTime 对象

我的日期服务有角度。我需要保留日期类型而不是使用字符串。

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

我的后端服务:

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

我有这个错误:

2019-08-06 08:21:02.185 WARN 1444 --- [nio-8080-exec-4] .wsmsDefaultHandlerExceptionResolver:已解决 [org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:无法 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 处找到的未解析文本;嵌套异常是 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”,

标签: javajsonangularspring-bootdate

解决方案


如何将 LocalDate 和 LocalDateTime 从 Angular 发送到 Spring

更好的解决方案:

app.module.ts

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

应用服务.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
    }); 
  }

弹簧件

@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) {) {
...
}

如果您只想转换 LocalDate ,您可以离开 datePipe 并从 Angular 发送 new Date().toISOString() 。但是由于提问者特别要求 LocalDate 你需要某种格式来获得这种 Date -> "yyyy-MM-dd" 。只有有了这个春天才能发挥它的魔力。

顺便提一句。如果您只需要 DateTimeFormat.ISO.TIME 的时间 (HH:mm:ss.SSSXXX),则同样可以。

结束!

不是很好的解决方案,更不舒服 -> 转换为字符串未测试,因为我对 Spring 解决方案很满意)

应用服务.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
    }); 
  }

春天:

@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...
}

推荐阅读