1.Java的String类型转换成Data日期类型
使用import java.text.SimpleDateFormat;
SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd ");
String s = "2020-09-09 ";
Date date = formatter.parse(s);
这里出现了pares报错,Unhandled exception: java.text.ParseException
需要继承 ParseException
2.SpringbootString类型转换成Data日期类型
2.1注解@JsonFormat(主要是后台到前台的时间格式的转换)
从数据库获取时间传到前端进行展示的时候,我们有时候可能无法得到一个满意的时间格式的时间日期,在数据库中显示的是正确的时间格式,获取出来却变成了很丑的时间戳,@JsonFormat注解很好的解决了这个问题,我们通过使用@JsonFormat可以很好的解决
//设置时区为上海时区,时间格式自己据需求定。
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
pattern:是你需要转换的时间日期的格式
timezone:是时间设置为东八区,避免时间在转换中有误差
提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别
2.2注解@DateTimeFormat(主要是前后到后台的时间格式的转换)
我们在使用WEB服务的时,可能会需要用到,传入时间给后台,比如注册新用户需要填入出生日期等,这个时候前台传递给后台的时间格式同样是不一致的,而我们的与之对应的便有了另一个注解,@DataTimeFormat
@DateTimeFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")