Java前后端的时间格式转换

在web项目中,前后端的数据类型不一致也是一个很常见的问题,最典型的莫过于时间格式的转换了,前端的时间展示一般是一个字符串类型(String),但是后端的时间类型则一般为日期类型(Date),在前端与后端交互的过程中,经常会涉及到String类型和Date类型的相互转换,现将两者之间的相互转换做一个小结:

前端->后端 一般就是字符串转日期类型,其常用方式为添加注解@InitBinder来实现不同类型对象的转换:

在controller中加入如下代码:

@InitBinder  
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标签格式化,如时间输入框往往需要对后端传过来的日期类型进行格式化

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

这样就完成了Date->String类型的格式转换。

扫描二维码关注公众号,回复: 2711982 查看本文章


猜你喜欢

转载自blog.csdn.net/w450093854/article/details/80299054