【问题标题】:Convert Date format in Java在 Java 中转换日期格式
【发布时间】:2019-08-03 23:12:51
【问题描述】:

我在 DTO 对象中有一个 Date 对象:

public class TopTerminalsDTO {

    private Date date;

    private int volume;

    private int count;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

当我在 Angular 中得到响应时,我得到了

count: 1
date: "2018-10-06T00:00:00.000+0000"
volume: 111

我想在 Angular 中获得这种日期格式 YYYY-MM-DD HH:mm:ss

将 Date 转换为 DTO 对象的正确方法是什么?使用 LocalDateTime 更好吗?

【问题讨论】:

标签: java spring-rest


【解决方案1】:

使用下面的代码。

Date myDate = new Date();
System.out.println(new SimpleDateFormat("YYYY-MM-DD HH:mm:ss").format(myDate));

【讨论】:

    【解决方案2】:

    LocalDate 是许多开发人员的首选方式,因为它是在 Java 8 中发布的。您可以使用 LocalDate.format(DateTimeFormatter) 方法以您想要的方式格式化 LocalDate 对象。

    喜欢这个例子来自:https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

    LocalDate date = LocalDate.now();
    String text = date.format(formatter);
    LocalDate parsedDate = LocalDate.parse(text, formatter);
    

    编辑

    LocalDate 类不提供时间表示。因此,如果您也想有时间,请使用LocalDateTime 课程。 LocalDateTime.format() 方法可以像LocalDate.format() 方法一样使用,如上所示。

    【讨论】:

    • 但我需要几小时和几分钟。使用 LocalDate 我只得到日期:“2018-11-06”。
    • 我添加了关于 LocalDateTime 的附加信息。您可以使用它在您的领域中也有时间表示。格式化程序的工作方式与 LocalDate 相同。
    【解决方案3】:

    最好使用 LocalDateTime 对象,但它会在日期和小时之间返回一个 T。您应该像在此处选择的答案中一样将其删除LocalDate - How to remove character 'T' in LocalDate

    【讨论】:

      【解决方案4】:

      你可以使用 DateFormat 来转换你想要的日期格式。

      TopTerminalsDTO tt = new TopTerminalsDTO();
      tt.setDate(new Date());
      String strDateFormat = "YYYY-MM-DD HH:mm:ss";
      DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
      String formattedDate= dateFormat.format(tt.getDate());
      System.out.println(formattedDate);
      

      当您将剩余对象发送到 Angular 时,您可以在 DTO 中使用字符串字段作为日期,一旦将其转换为所需日期格式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-15
        • 2012-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多