java - 如何在 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
解决方案
我想不出任何充分的理由不将日期保存在日期对象以外的任何地方。(如上所述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
}
推荐阅读
- gatsby - Gatsby 还没有页面
- ios - 在响应中附加重复的数组项(Swift)
- php - docker 容器性能中的 Php-fpm 和 Nginx
- python - 我们可以从 python 程序的任何部分访问变量的值吗?
- php - 用户登录后如何显示单个用户的个人资料?
- python - 从数据框中计算字典查找
- java - 如何仅更改日期字符串中的年份?
- html - 如何将我的应用的视口大小减少到 chrome 浏览器视图的 67%?
- server - .NetCore 处理多环境问题 - ASPNETCORE_ENVIRONMENT 始终在主机服务器上进行生产
- python - 为什么 requests.get() 在 Python 中返回过时的网站?