将日期从时间戳转换为实体构造函数中的人类可读

时间:2017-02-15 14:15:21

标签: java spring date spring-mvc spring-boot

目前,存储的Date requestDate变量的格式如下:2017-02-17 00:00:00.0。我想将其转换为,例如:Friday, February 17, 2017。我想在我的实体中进行转换并返回它,以便在显示它时更具人性化。这可能发生在构造函数中,在这一行:this.setRequestDate(doDateConversion(requestDate));。如何进行此转换?

我的请求实体:

@Entity
@Table(name = "Request")
public class RequestDO implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="request_id")
    private Long id;
    private Date requestDate;
    private String description;
    private RequestStatus status;
    /*private Boolean read;*/
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id", nullable = false)
    private Users users;

    public RequestDO() {}

    public RequestDO(Users user, Date requestDate) {
        this.setUsers(user);
        this.setRequestDate(requestDate);
    }

    @Override
    public String toString() {
        return String.format(
                "RequestDO[id=%d, inital='%s', requestDate='%s']",
                getId()
                , getUsers().getInitialName()
                , getRequestDate());
    }


    public Date getRequestDate() {
        return requestDate;
    }

    public void setRequestDate(Date requestDate) {
        this.requestDate = requestDate;
    }
}

3 个答案:

答案 0 :(得分:2)

您可以使用SimpleDateFormat将日期转换为您选择的可读字符串。

示例的时间格式字符串为EEEE, MMMM, dd, yyyy。您必须创建一个新的SimpleDateFormat对象并将日期格式化为String。 Examples...

但是Spring提供了一些开箱即用的特价。例如,您可以将杰克逊用于日期格式:@JsonFormat(pattern="yyyy-MM-dd") more。也可以在application.properties文件中添加数据格式:spring.jackson.date-format

答案 1 :(得分:1)

使用SimpleDateFormat

java.sql.Date date = new Date(System.currentTimeMillis());
System.out.println(new SimpleDateFormat("EEEE, MMMM dd, YYYY").format(date));

有关详细信息,请参阅this

答案 2 :(得分:0)

我通过使用SimpleDateFormat在控制器中读取日期来更改日期来解决问题:

@RequestMapping(value = "/requests", method = RequestMethod.GET)
    public String getAllRequests(Model model, RequestModel requestModel) throws ParseException {
        List<RequestDO> requestDOArrayList = new ArrayList<RequestDO>();
        for (RequestDO requestDO : requestRepository.findAll()) {
            log.info(requestDO.toString());

            // Display all dates in Requests list in human-readable form
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(requestDO.getRequestDate().toString());
            log.info(String.valueOf(date));
            requestDO.setRequestDate(date);

            requestDOArrayList.add(requestDO);
        }
        model.addAttribute("requests", requestDOArrayList);
        log.info(requestDOArrayList.toString());
        return "requests";
    }