如何将mysql数据库中的DateTime数据类型拿出来

本文介绍了在Java中从数据库获取时间数据时遇到的问题。原始方法将DateTime转换为String时产生了多余的'.0'。通过调整代码,使用Date类型和SimpleDateFormat进行格式化,成功解决了问题,确保了时间信息的正确显示。
摘要由CSDN通过智能技术生成

最近在开发时,需要将数据库存储的时间拿出来显示给接口。刚开始我是直接用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”
}

这种方式获取的时间信息明显没问题。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值