首页 > 解决方案 > 如何在 Java 中将日期格式转换为 dd-MM-yyyy 并返回 Date 对象

问题描述

我正在制作一个以 dd-MM-yyyy 格式处理日期的 API。但是使用 Date 对象我得到 yyyy-MM-dd 格式。我尝试通过多种方式更改日期格式,例如此代码-

package com.example.internshala.model;


import com.fasterxml.jackson.annotation.JsonProperty;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


public class Ship {

    private String loadingPoint;
    private String unloadingPoint;
    private String productType;
    private String truckType;
    private int noOfTrucks;
    private int weight;
    private String comment;
    private UUID shipperId;
    private String date;

    //--------------------------------------
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

    //--------------------------------------

    public String getLoadingPoint() {
        return loadingPoint;
    }


    public String getUnloadingPoint() {
        return unloadingPoint;
    }


    public String getProductType() {
        return productType;
    }


    public String getTruckType() {
        return truckType;
    }


    public int getNoOfTrucks() {
        return noOfTrucks;
    }


    public int getWeight() {
        return weight;
    }


    public String getComment() {
        return comment;
    }


    public UUID getShipperId() {
        return shipperId;
    }


    public String getDate() {
        return date;
    }


    public Ship(@JsonProperty("loadingPoint") String loadingPoint,
                @JsonProperty("unloadingPoint") String unloadingPoint,
                @JsonProperty("productType") String productType,
                @JsonProperty("truckType") String truckType,
                @JsonProperty("noOfTrucks") int noOfTrucks,
                @JsonProperty("weight") int weight,
                @JsonProperty("comment") String comment,
                @JsonProperty("shipperId") UUID shipperId,
                @JsonProperty("Date") Date date) {
        this.loadingPoint = loadingPoint;
        this.unloadingPoint = unloadingPoint;
        this.productType = productType;
        this.truckType = truckType;
        this.noOfTrucks = noOfTrucks;
        this.weight = weight;
        this.comment = comment;
        this.shipperId = shipperId;
        String newDate=date.toString();
        this.date=formatter.format(newDate);



    }
}

我还将它应用于直接 Date 对象作为构造函数参数,但它给出错误 - com.fasterxml.jackson.databind.exc.ValueInstantiationException

标签: javaspringspring-bootrest

解决方案


我想不出任何充分的理由不将日期保存在日期对象以外的任何地方。(如上所述Date已过时,因此LocalDate是更好的选择。)

根据我在您的代码中看到的内容,您正在使用 jackson 来读取/写入文件。而不是更改您自己的类,因此它会在文件中输出您期望的内容,您更改正在使用的库,在本例中为杰克逊,以您希望它们的格式写入和读取值。

你有很多不同的方法来做到这一点。例如,您可以将格式设置为默认格式,如下所示:

DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
objectMapper.setDateFormat(df);

或者您只为一个属性更改它

public class Ship {
    // Code
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    private Date date;
    // Code
}

推荐阅读