前台使用的input标签的datetime-local类型往后台传时间,但是数据库使用的是TimeStamp格式,所以要经过转换。
前台的标签:
<form action="${path}/manage/borrow/test" method="post">
<input type="datetime-local" name="time">
<input type="submit" value="提交">
</form>
标签样式:
datatime-local格式用String类型接收会是完整的,然后将中间的"T"替换掉,转成Date格式再转成TimeStamp格式。
后端Controller的方法:
//test
@PostMapping("/test")
public void test(String time){
System.out.println(time+" 前台传过来的时间");
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(time.replaceAll("T", " ") + ":00", df);
System.out.println(localDateTime+" localDateTime格式的时间");
Date date = Date.from( localDateTime.atZone( ZoneId.systemDefault()).toInstant());
System.out.println(date+" Date格式的时间(java.util的包)");
Timestamp timestamp = new Timestamp(date.getTime());
System.out.println(timestamp+" Timestamp格式的时间(java.sql的包)");
}
输出的结果为:
如果有简单的方法,请在评论区留言,谢谢!