1.首先是MySQL与Java的时间格式对应图

2.四种时间格式的选择

  • date 只有年月日
  • datetime 最完整 也是最占内存的
  • timestamp 较完整,但是最大上限是2038年
  • time 只表示时间
  • year 只表示年

3.在Spring中自动时间的转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package kid1999.upload.model;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.sql.Timestamp;


@Data
@TableName("homework")
public class HomeWork {

@TableId(type = IdType.AUTO) // 自增
private int id;
private String title;
private String infomation;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Timestamp createtime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Timestamp endtime;
private String type;
}
  • JsonFormat 负责前端和后端的转换 json <-> class
  • DateTimeFormat 负责后端与数据库的转换 class <-> row