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

时间:2014-09-15 12:09:48

标签: java mysql

我有如下表格,

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 。我在做错了吗?

1 个答案:

答案 0 :(得分:4)

您正在将ab转换为毫秒(自纪元以来),然后获得差异。由于您的后续行涉及调用Time constructor,因此您不需要将时间缩短为24 * 60 * 60 * 1000。仅将c值作为差异(以毫秒为单位),然后将其转换为下一行中的Time对象diff

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

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

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

  

我建议你让MySQL在你的查询中为你做数学计算,例如SELECT Lunch_Out,After_Lunch_In,subtime(After_Lunch_In,Lunch_Out)作为Lunch_Duration FROM ....有关详细信息,请参阅Paul。 / p>