关于时间格式化和格式转换

第一部分:

数据提交时的时间格式化:

在接受日期数据的实体类的时间属性上添加Spring的 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") 注解,则该属性在接收到时间数据时将其格式化为 pattern 对应的格式

注意:SpringBoot在接受来自前端的时间参数是不会自动将字符串型转为 Date 型,会报 org.springframework.core.convert.ConversionFailedException 这个异常,异常信息是: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2020-09-24' ,此时使用 @DateTimeFormat(pattern="yyyy-MM-dd") 注解可以实现自动将json数据中的时间字符串转为 Date 型数据

以上是到日期的案例,如果是要到时分秒,只需要传相应的时间参数,配置 pattern 相应的格式化时间格式即可

数据在页面展示时的时间格式化:

1.在展示日期数据的实体类的时间属性上添加Spring的 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") 注解,则该属性在转为json数据时会格式化为 pattern 对应的格式

2.在 application.yaml 文件中格式化时间:

1 spring: 
2     mvc: 
3         ## mvc格式化时间的格式
4         date-format: yyyy-MM-dd hh:mm:ss
5     jackson: 
6         ## json格式化时间的格式
7         date-format: yyyy-MM-dd hh:mm:ss

进行配置之后,前端页面接受的json数据的时间格式都会是格式化形式的时间格式

注意:在配置文件中配置了mvc格式化时间格式后,在向后端发送数据时也要是格式化类型的时间格式,否则会出错,原因是springboot在解析json字符串中的时间时会以配置mvc时间格式化形式进行解析,如果格式不匹配就会出错,类似第三部分的字符串向日期转化。

使用 @JSONFormat 注解,给 pattern 赋格式化值,本人未曾使用,使用可以参考:https://blog.csdn.net/badguy_gao/article/details/82853895

具体格式化的时间是后端接受还是发送留待后续测试

其他方式以及需要后续深入学习的手记:https://www.imooc.com/article/301447

第二部分:

jsp页面的时间和后端时间的格式转换

以下内容转自:https://blog.csdn.net/w450093854/article/details/80299054?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

前端到后端---------------->字符串转日期(未曾了解和使用)

在controller中加入如下代码:

1 @InitBinder  
2 public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); }

则在前端传入yyyy-MM-dd格式的字符串时,系统会自动将其转换为Date类型的对象。这可以实现String->Date的转换。

后端到前端---------------->日期转字符串

常用的方式是在jsp页面引入标签

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

然后对需要转换的字段采用fmt标签格式化,如时间输入框往往需要对后端传过来的日期类型进行格式化

1 <input type="text"  id = "startDate" name="startDate" value = "<fmt:formatDate value="${searchVO.startDate}" pattern="yyyy-MM-dd" />"   >

第三部分:

后端时间的表示方式有多种,long型的毫秒数,Date型的日期,字符串类型的格式。三者之间是如何转换的

以下内容转自:https://blog.csdn.net/weixin_38366182/article/details/80735773

1.Long型转Date型:

1 Date date = new Date(Long timeLong);

2.Date型转Long型

1 Date date = new Date(); 
2 Long timeLong = date.getTime();

3.Date型转String型

1 Date date = new Date();
2 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
3 String timeStr = sdf.format(date);

4.String型转Date型

1 String timeStr = "2020-09-29 10:00:00";
2 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
3 try{
4     // 时间字符串的格式不匹配会报异常
5     Date date = sdf.parse(timeStr);
6 }catch(ParseException e){
7     e.printStackTrace();
8 }
原文地址:https://www.cnblogs.com/xiao-lin-unit/p/13563639.html