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

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

Setting Date Value in Controller of Spring Boot Application (Java 8)

问题

  1. 在我的模型中我有以下内容

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

  1. 我试图按以下方式输出一个对象数组:

@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)),

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

In my model I have the following:

  1. private Date exampleDate;
  2. public Testing(Date exampleDate) {
  3. this.exampleDate = exampleDate;
  4. }
  5. public Date getExampleDate() {
  6. return (Date) this.exampleDate.clone();
  7. }
  8. public void setExampleDate(Date exampleDate) {
  9. this.exampleDate = (Date) exampleDate.clone();
  10. }

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

  1. @RestController
  2. public class TestingController {
  3. @GetMapping(&quot;/saved&quot;)
  4. public List&lt;Testing&gt; getData() {
  5. List&lt;Testing&gt; savedDatas = new ArrayList&lt;&gt;(Arrays.asList(
  6. new Testing(
  7. 1,
  8. &quot;Text&quot;,
  9. 2000-1- 1),
  10. new Testing(
  11. 2,
  12. &quot;Text2&quot;,
  13. 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

我建议您使用更新的类:

  1. LocalDateTime

  1. ZonedDateTime

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

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

I would suggest you use the newer classes:

  1. LocalDateTime

and

  1. ZonedDateTime

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

  1. LocalDateTime.of(date, time); //or
  2. 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:

确定