时间类型在我们的项目中经常会遇到,最笨的办法就是先用字符串接受时间戳,然后再转为java中的Date类型
那怎么能更优雅的解决这个问题呢?
spring 其实已经为我们做出了很方便的处理

// 获取提交参数
	@PostMapping("/format/date")
	@ResponseBody
	public Map<String, Object> format(Date date) {
		Map<String, Object> dataMap = new HashMap<>();
		dataMap.put("date", date);
		return dataMap;
	}

这里我们去接受Date类型
我们只需要在配置文件中添加这么一句话

spring.mvc.date-format=yyyy-MM-dd HH:mm:ss

现在再去测试
参数为:[{“key”:“date”,“value”:“2018-2-10 11:20:13”}]
我们发现spring后台会自动帮我们将传递过来的数据转为Date类型

坑点:
默认有时区问题,接受为Date类型的时间比现实时间少了8个小时
配置:spring.jackson.time-zone: GMT+8
这样就是正确的时间了

更多推荐

spring mvc 参数接收Date类型