【Java/jdbc/oracle】将两Timestamp字段的差值变成时分秒毫秒的形式
【代码】
package com.hy.lab.timestampdiff; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; public class Test { public static void main(String[] args) throws Exception{ final String sql="select id,start_time,end_time from emp73 order by id"; try(Connection conn=DbUtil.getConn(); PreparedStatement pstmt=conn.prepareStatement(sql)){ ResultSet rs=pstmt.executeQuery(); while(rs.next()){ int id=rs.getInt(1); Date startDate=rs.getDate(2); Date endDate=rs.getDate(3); System.out.println(String.format("%d-%s",id,getDhms(startDate,endDate))); } }catch(Exception ex){ ex.printStackTrace(); } } private static String getDhms(Date startDate,Date endDate){ return ms2DHMS(startDate.getTime(),endDate.getTime()); } private static String ms2DHMS(long startMs, long endMs) { String retval = null; long secondCount = (endMs - startMs) / 1000; String ms = (endMs - startMs) % 1000 + "ms"; long days = secondCount / (60 * 60 * 24); long hours = (secondCount % (60 * 60 * 24)) / (60 * 60); long minutes = (secondCount % (60 * 60)) / 60; long seconds = secondCount % 60; if (days > 0) { retval = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { retval = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { retval = minutes + "m" + seconds + "s"; } else if(seconds > 0) { retval = seconds + "s"; }else { return ms; } return retval + ms; } }
【输出】
1-1s0ms 2-1m1s0ms 3-1h0m1s0ms 4-1d0h0m1s0ms 5-31d0h0m1s0ms
注:如果毫秒不需要可以到ms2DHMS中进行调整。
【建表及充值】
create table emp73( id number(3), start_time timestamp, end_time timestamp, primary key(id) ); insert into emp73(id,start_time,end_time) values(1,to_date('20220701 12:23:34','yyyymmdd hh24:mi:ss'),to_date('20220701 12:23:35','yyyymmdd hh24:mi:ss')); insert into emp73(id,start_time,end_time) values(2,to_date('20220701 12:23:34','yyyymmdd hh24:mi:ss'),to_date('20220701 12:24:35','yyyymmdd hh24:mi:ss')); insert into emp73(id,start_time,end_time) values(3,to_date('20220701 12:23:34','yyyymmdd hh24:mi:ss'),to_date('20220701 13:23:35','yyyymmdd hh24:mi:ss')); insert into emp73(id,start_time,end_time) values(4,to_date('20220701 12:23:34','yyyymmdd hh24:mi:ss'),to_date('20220702 12:23:35','yyyymmdd hh24:mi:ss')); insert into emp73(id,start_time,end_time) values(5,to_date('20220701 12:23:34','yyyymmdd hh24:mi:ss'),to_date('20220801 12:23:35','yyyymmdd hh24:mi:ss'));
END
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2017-07-03 C# 将链表存入二进制文件及读取二进制文件得到链表示例
2017-07-03 C# 将long类型写入二进制文件用bw.Write(num);将其读出用long num= br.ReadInt64();
2015-07-03 【Canvas与艺术】黄色立体感放射光芒五角星