在Java中设置Date字段的格式,通常有两种常见做法:
1. 在实体类中使用注解格式化(推荐)
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class YourEntity {
// 方案1: Jackson注解(适用于JSON序列化)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date entryDate;
// 方案2: Spring注解(适用于表单绑定)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date entryDate;
// 方案3: 使用LocalDateTime(Java 8+推荐)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime entryDateTime;
// getter和setter
public Date getEntryDate() {
return entryDate;
}
public void setEntryDate(Date entryDate) {
this.entryDate = entryDate;
}
}
2. 在配置文件中全局设置
application.yml/application.properties:
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
3. 手动格式化(灵活控制)
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
// 日期转字符串
public static String formatDate(Date date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}
// 字符串转日期
public static Date parseDate(String dateStr, String pattern) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.parse(dateStr);
} catch (Exception e) {
throw new RuntimeException("日期格式错误");
}
}
}
// 使用示例
String formattedDate = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
Date date = DateUtil.parseDate("2024-01-15 14:30:00", "yyyy-MM-dd HH:mm:ss");
4. 使用Java 8的日期时间API(强烈推荐)
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class YourEntity {
private LocalDateTime entryDate;
// 格式化显示
public String getFormattedEntryDate() {
if (entryDate == null) return null;
return entryDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
// 字符串设置
public void setEntryDateFromString(String dateStr) {
this.entryDate = LocalDateTime.parse(dateStr,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}
常用格式模式
| 格式 | 说明 | 示例 |
|---|---|---|
| yyyy-MM-dd | 年-月-日 | 2024-01-15 |
| yyyy/MM/dd | 年/月/日 | 2024/01/15 |
| yyyy-MM-dd HH:mm:ss | 完整日期时间 | 2024-01-15 14:30:00 |
| yyyy年MM月dd日 | 中文日期 | 2024年01月15日 |
| HH:mm:ss | 时间 | 14:30:00 |
| yyyy-MM-dd'T'HH:mm:ss | ISO格式 | 2024-01-15T14:30:00 |
最佳实践建议
-
后端到前端传输 :使用
@JsonFormat注解 -
前端到后端接收 :使用
@DateTimeFormat注解 -
数据库存储 :使用
LocalDateTime(Java 8+) -
时区处理 :明确指定时区,如
timezone = "GMT+8"
选择哪种方式取决于你的具体需求:
-
如果主要在JSON接口中使用,选方案1
-
如果需要灵活控制,选方案3
-
如果是新项目,强烈推荐使用Java 8的日期时间API(方案4)