在Spring Boot应用程序的控制器中设置日期值(Java 8)

huangapple go评论58阅读模式
英文:

Setting Date Value in Controller of Spring Boot Application (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 getData() {
List savedDatas = new ArrayList<>(Arrays.asList(
new Testing(
1,
"Text",
new Date(2000, 1, 1)),
new Testing(
2,
"Text2",
new Date(2019, 3, 27)),


我尝试使用了`new Date`,但是它不起作用,那么作为类型为`Date`的第三个参数,我需要传递什么内容呢?不是字符串或整数!
英文:

In my model I have the following:

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

And I am trying to output an array of objects as follows

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

I tried to use new Date but that doesn't work, so what exactly do I need to pass as the third argument as type Date instead of String or int?!?!

答案1

得分: 1

我建议您使用更新的类:

LocalDateTime

ZonedDateTime

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

LocalDateTime.of(date, time); //或者
LocalDate.of(date);
英文:

I would suggest you use the newer classes:

LocalDateTime

and

ZonedDateTime

Then you can get a LocalDateTime instance by using the static factory methods:

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

huangapple
  • 本文由 发表于 2020年9月21日 19:23:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63991270.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定