springmvc中对日期格式化的处理

@DateTimeFormat(pattern="yyyy-MM-dd")

     返回的时候java.util.Date

     pattern="yyyy-MM-dd"必须要和页面中的日期格式对应。

1、TimeController.java

 1 package com.chenk.web.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.ui.Model;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 
 7 import com.chenk.pojo.Users;
 8 
 9 @Controller
10 public class TimeController {
11 @RequestMapping("/addUserController")
12 public String addUser(Users user,Model model){
13     model.addAttribute("user", user);
14     System.out.println(user);
15     return "showUser";
16 }
17 }

2.User.java

 1 package com.chenk.pojo;
 2 
 3 import java.util.Date;
 4 
 5 import org.springframework.format.annotation.DateTimeFormat;
 6 
 7 public class Users {
 8 private String name;
 9 private String age;
10 //备用yyyy-MM-dd HH:mm:ss
11 @DateTimeFormat(pattern="yyyy-MM-dd")
12 private Date birth;
13 public String getName() {
14     return name;
15 }
16 public void setName(String name) {
17     this.name = name;
18 }
19 public String getAge() {
20     return age;
21 }
22 public void setAge(String age) {
23     this.age = age;
24 }
25 public Date getBirth() {
26     return birth;
27 }
28 public void setBirth(Date birth) {
29     this.birth = birth;
30 }
31 @Override
32 public String toString() {
33     return "Users [name=" + name + ", age=" + age + ", birth=" + birth + "]";
34 }
35 
36 }

3、页面

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>日期</title>
 8 
 9 </head>
10 <body>
11     <form action="addUserController" method="post">
12         <input type="text" name="name" /> 
13         <input type="text" name="age" /> 
14         <input type="text" name="birth" /> 
15         <input type="submit" value="提交">
16     </form>
17 </body>
18 </html>

 

posted @ 2017-12-04 22:40  Jony.K.Chen  阅读(5545)  评论(0编辑  收藏  举报