pojo属性
注意这里Date导的包可以是util的也可以是sql 一般是sql 本方法两个包都适用
public class Student {
private Integer id;
private String name;
private Date birthday;
private Integer gid;
private String gname;
private Integer count;
private Integer cptime;
private String birString;
数据库信息
其中birthday设计的是date类型
如果按正常流程从库中拿所有信息 并转化成为json格式 如下
[{"birString":"1998-01-01","birthday":883584000000,"count":2,"cptime":3,"gname":"1401","id":1,"name":"张三"},{"birString":"1999-02-01","birthday":917798400000,"count":1,"cptime":2,"gname":"1401","id":2,"name":"李四"},{"birString":"2000-01-01","birthday":946656000000,"count":1,"cptime":3,"gname":"1402","id":3,"name":"王五"}]
birthday为一串字符串
然而我们需要的是以数据库中的格式在页面展现出来
因此我们在dao层拿到数据以后需要在service层对数据进行格式转换
我这里用的easyUI呈现的页面 代码如下
<table id="dg" title="选课信息" class="easyui-datagrid" fitColumns="true"
pagination="true" url="stuServlet?method=getStuList" fit="true" toolbar="#tb">
<thead>
<tr>
<th field="cb" checkbox="true"></th>
<th field="id" width="50">学生编号</th>
<th field="name" width="100">学生姓名</th>
<th field="birString" width="250">birthday</th>
<th field="gname" width="100">班级名称</th>
<th field="count" width="100">已选课数</th>
<th field="cptime" width="100">所选课时</th>
</tr>
</thead>
</table>
可以看到我的student属性中还有一个
private String birString
这个属性就是用来将转换格式后的birthday set属性到birString中然后在easyUI中展现到页面
接下来就是最关键的部分 怎样将格式进行转换
附上service层中的代码
public List<Student> getStuList() throws SQLException {
// TODO Auto-generated method stub
List<Student> list = studentDao.getStuList();
for (Student student : list) {
//将数据进行格式化,按照一定的格式,比如xxxx年xxxx月xxxx日
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//将util.Date转换成为sql.Date,在Date.valueOf(String str)中发生了 util.Date.toSting(),就将Date类型转换成了String类型的字符串
Date birthString=Date.valueOf(student.getBirthday().toString());
//利用simpleDateFormat.format()方法进行格式输出,他的作用就是按照第一步的格式进行输出时间
student.setBirString(simpleDateFormat.format(birthString));
}
return list;
}
这样就ok啦
最终页面如下