【问题标题】:Converting two LocalTime objects into a Duration object将两个 LocalTime 对象转换为 Duration 对象
【发布时间】:2018-01-20 04:56:51
【问题描述】:

Joda 是必须的,因为 Java SE8 在此环境中不可用。

如何找出两个LocalTime 对象之间的小时差,并将其存储为Duration?尝试了以下没有运气:

LocalTime startTime = new LocalTime(8, 0);
LocalTime endTime = new LocalTime(16, 0);

Period shiftDuration = new Period(0, 
endTime.getHourOfDay() - startTime.getHourOfDay(), 0, 0);

System.out.println(shiftDuration.getHours()); // expected 8, get 0.

【问题讨论】:

    标签: java jodatime datediff


    【解决方案1】:

    您在错误的参数中提供了值。试试这个:

    LocalTime startTime = new LocalTime(8, 0);
        LocalTime endTime = new LocalTime(16, 0);
    
        Period shiftDuration = new Period(endTime.getHourOfDay() - startTime.getHourOfDay(), 0, 0, 0);
    
        System.out.println(shiftDuration.getHours());
    

    根据JODA documentation

    Period(int hours, int minutes, int seconds, int millis) 
              Create a period from a set of field values using the standard set of fields.
    

    【讨论】:

      【解决方案2】:

      如果您特别想知道这 2 个 LocalTime 实例之间的小时数,您可以使用 org.joda.time.Hours 类:

      LocalTime startTime = new LocalTime(8, 0);
      LocalTime endTime = new LocalTime(16, 0);
      
      int hours = Hours.hoursBetween(startTime, endTime).getHours();
      

      结果将是8

      您也可以使用org.joda.time.Period

      Period period = new Period(startTime, endTime);
      System.out.println(period.getHours()); // 8
      

      结果也是8

      它们之间的区别在于 Hours 对值进行四舍五入,但 Period 不进行四舍五入。示例:

      // difference between 08:00 and 16:30
      LocalTime startTime = new LocalTime(8, 0);
      LocalTime endTime = new LocalTime(16, 30);
      
      Period period = new Period(startTime, endTime);
      System.out.println(period); // PT8H30M
      System.out.println(period.getHours()); // 8
      System.out.println(period.getMinutes()); // 30
      
      int hours = Hours.hoursBetween(startTime, endTime).getHours();
      System.out.println(hours); // 8
      

      Period 保留所有字段(8 小时 30 分钟),而 Hours 只关心小时并丢弃其他字段。

      【讨论】:

      • 内容丰富,您实际上回答了我昨天也遇到的一个小问题。非常感谢您分享您的专业知识!
      猜你喜欢
      • 2021-08-14
      • 1970-01-01
      • 2018-08-27
      • 2023-04-03
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 2017-10-15
      相关资源
      最近更新 更多