最近在开发时,需要将数据库存储的时间拿出来显示给接口。刚开始我是直接用String类型获取的DateTime数据。直接上代码:
DAO层数据库操作层代码:
@Query(value = "select t.create_time as createTime from t_track t where t.id=?1 ",nativeQuery = true)
public String getTrackCreateTime(Long id);
Service层获取时间代码
public String test(Long id){
String createTime=trackRepository.getTrackCreateTime(id);
return createTime;
}
这样收到的返回值代码是
{
“createTime”: “2021-01-27 21:08:28.0”
}
很明显,时间后面多出一个小数点,因此这种方法不是最优解。
可以直接用第二种方法,直接上代码:
Dao层代码:
@Query(value = "select t.create_time as createTime from t_track t where t.id=?1 ",nativeQuery = true)
public Date getTrackCreateTime(Long id);
Service层代码:
public String test(Long id){
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date time=trackRepository.getTrackCreateTime(id);
String createTime=dateFormat.format(time);
return createTime;
}
{
“createTime”: “2021-01-27 21:08:28”
}
这种方式获取的时间信息明显没问题。