首页 > 解决方案 > 在 Spring Boot 应用程序的控制器中设置日期值(Java 8)

问题描述

在我的模型中,我有以下内容:

private Date exampleDate;

public Testing(Date exampleDate) {
        this.exampleDate = exampleDate;
    }

public Date getExampleDate() {
        return (Date) this.exampleDate.clone();
    }

    public void setExampleDate(Date exampleDate) {
        this.exampleDate = (Date) exampleDate.clone();
    }

我正在尝试输出一个对象数组,如下所示

@RestController
public class TestingController {
    @GetMapping("/saved")
    public List<Testing> getData() {
        List<Testing> savedDatas = new ArrayList<>(Arrays.asList(
                new Testing(
                        1,
                        "Text",
                        2000-1- 1),
                new Testing(
                        2,
                        "Text2",
                        new Date(27 / 03 / 19)),

我尝试使用 new Date 但这不起作用,那么我到底需要将什么作为第三个参数作为 typeDate而不是 String 或 int 传递?!?!

标签: javaspring-bootapigradlejava-8

解决方案


我建议您使用较新的类:

LocalDateTime

ZonedDateTime

然后您可以使用静态工厂方法获取 LocalDateTime 实例:

LocalDateTime.of(date, time); //or
LocalDate.of(date);

推荐阅读