我正在制作一個以 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
uj5u.com熱心網友回復:
你應該改變
String newDate=date.toString();
this.date=formatter.format(newDate);
到
this.date=formatter.format(date);
uj5u.com熱心網友回復:
我想不出有什么好的理由不將日期保存在日期物件以外的任何內容中。(如前所述Date已經過時,因此LocalDate是更好的選擇。)
從我在您的代碼中看到的內容來看,您正在使用 jackson 來讀/寫檔案。而不是更改您自己的類,因此它將輸出您在檔案中期望的內容,您更改您正在使用的庫,在本例中為 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
}
uj5u.com熱心網友回復:
匯入 java.text.SimpleDateFormat; 匯入 java.util.Date;
public class SamDateFormat
{
public static void main(String[] args)
{
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String currDate= formatter.format(date);
System.out.println(currDate);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/334513.html
上一篇:org.springframework.beans.factory.BeanCreationException:創建名為“roleRepository”的bean時出錯
