代码之家  ›  专栏  ›  技术社区  ›  Shirwyn

hoursBetween给出的答案值太大

  •  -1
  • Shirwyn  · 技术社区  · 7 年前

    我真的不知道我的代码出了什么问题。我在这个案子上使用的是Joda Time api。此代码位于rs.next()之后,我需要以整数形式获取hh的值,因为我必须将其乘以停车服务的小时费率。

    java.sql.Time timeOut = new java.sql.Time(new java.util.Date().getTime());
    java.sql.Time timeIn = rs.getTime("timeIn");
    DateTime d2 = new DateTime(timeOut);//Value is 18:39:24
    DateTime d1 = new DateTime(timeIn);//Value is 16:03:50
    int hh = Hours.hoursBetween(d1,d2).getHours();
    txtDuration.setText(""+hh);//Display on textbox and shows 421946
    

    我也试过这个

    Duration duration = new Duration(d1,d2);
    long ss = duration.getStandardSeconds();
    long mm = ss/60;
    long hh = mm/60;
    

    早上好,提前谢谢你。

    3 回复  |  直到 7 年前
        1
  •  3
  •   gpeche    7 年前

    从…起 java.sql.Time javadoc

    日期组件应设置为1970年1月1日的“零历元”值,并且不应访问。

    然后,在代码中

    java.sql.Time timeOut = new java.sql.Time(new java.util.Date().getTime());
    

    new java.util.Date() 一般来说,不会是1970年1月1日,所以实际上您正在创建一个无效 java.sql.Time 例子可能在幕后发生的是,你正在计算1970年1月1日(你的 timeIn ,这是来自数据库的,可以假定是正确的)以及 马上 :

    421946小时=421946/24天~17581天~17581/365年~48年。

    1970+48=2018,今年。

        2
  •  0
  •   Vlad Bochenin Rom4in    7 年前

    看起来你没有 Date 参与 timeIn 以DB为单位的列。

    Hours.hoursBetween(DateTime.parse("1970-01-01T16:03:50"), DateTime.parse("2018-02-19T18:39:24")).getHours()  == 421946
    

    如果您想比较时间(不含日期部分),可以使用 LocalTime 来自joda图书馆。

    LocalTime d2 = new LocalTime(timeOut.getTime());
    LocalTime d1 = new LocalTime(timeIn.getTime());
    

    或指定适当的日期:

    d1.withDate(<put proper date here>)
    
        3
  •  0
  •   Anonymous    7 年前

    虽然我对Joda Time没有经验,但我知道 java.time 答复:

        LocalTime timeOut = LocalTime.now(ZoneId.of("Africa/Khartoum"));
        LocalTime timeIn = rs.getObject("timeIn", LocalTime.class);
        int hh = (int) ChronoUnit.HOURS.between(timeIn, timeOut);
    

    您确定从数据库中知道时间的时区吗?“现在”是一个非常敏感的时区概念,因此如果您的时区不匹配,您可能会得到任何错误的结果。相信您确实知道,如果不是非洲/喀土穆,请替换正确的时区。你确定时间是在同一天吗?您可以尝试以下更正:

        if (timeOut.isBefore(timeIn)) {
            hh += 24;
        }
    

    它显然有其局限性。如果时间相隔几天,那就行不通了。最后,你知道如果在夏季时间(DST)和 timeIn timeOut ?

    你以为是你在问这个问题

    略读 the documentation of org.joda.time.LocalTime 在我看来,您可以以类似的方式使用该类,构建 超时 使用无参数构造函数和 timeIn公司 使用 LocalTime(Object instant) 构造函数。