gpt4 book ai didi

java - 如何计算两个 java.sql.Time 值之间的差异?

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:12 24 4
gpt4 key购买 nike

我有如下表格,

id | Lunch_Out | After_Lunch_In

01 | 01:15:00 | 02:00:01

我正在尝试使用以下代码查找时差,

while(rst.next())
{
PrintWriter obj1 = response.getWriter();
obj1.println("while entered");

Time a =rst.getTime("Lunch_Out");
Time b =rst.getTime("After_Lunch_In");

PrintWriter objt1 = response.getWriter();
objt1.println("LougOut Time is :"+b);
PrintWriter objt2 = response.getWriter();
objt2.println("LogIn Time is :"+a);

//long c = b.getTime() - a.getTime()

long c = b.getTime() - a.getTime() / (24 * 60 * 60 * 1000);

//PrintWriter objtr = response.getWriter();
//objtr.println("different is :"+c);

Time diff = new Time(c);

PrintWriter objt = response.getWriter();
objt.println("different is :"+diff);

}

输出是:

while entered

LougOut Time is :02:00:02

LogIn Time is :01:15:01

different is :02:00:02

但预期输出是:00:45:01。我在哪里做错了?

最佳答案

您正在将 ab 都转换为毫秒(从纪元开始),然后求出差异。由于您的后续行涉及调用 Time constructor ,因此您不需要像您所做的那样通过除以 24 * 60 * 60 * 1000 来将时间扩展到几天。仅将c 值作为毫秒差值,然后将其转换为下一行中的Time 对象diff

更新后的代码应如下所示。

long c = b.getTime() - a.getTime();
Time diff = new Time(c);

但是,这将为您提供一个具有正确小时数、分钟数和秒数但日期为 1970 年 1 月 1 日的 Time 对象。由于您已将 MySQL 标记添加到您的问题中,我建议您考虑 Paul '在他的评论中提出了建议。

I suggest you let MySQL do the math for you as part of your query, something like SELECT Lunch_Out, After_Lunch_In, subtime(After_Lunch_In, Lunch_Out) as Lunch_Duration FROM .... See the MySQL reference manual for details.

关于java - 如何计算两个 java.sql.Time 值之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25847798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com