Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将两个LocalTime对象转换为Duration对象_Java_Jodatime_Datediff - Fatal编程技术网

Java 将两个LocalTime对象转换为Duration对象

Java 将两个LocalTime对象转换为Duration对象,java,jodatime,datediff,Java,Jodatime,Datediff,Joda是必须的,因为JavaSE8在此环境中不可用 如何查找两个LocalTime对象之间的小时差,以存储为持续时间?尝试了以下操作但没有成功: LocalTime startTime = new LocalTime(8, 0); LocalTime endTime = new LocalTime(16, 0); Period shiftDuration = new Period(0, endTime.getHourOfDay() - startTime.getHourOfDay(), 0

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

如何查找两个
LocalTime
对象之间的小时差,以存储为
持续时间
?尝试了以下操作但没有成功:

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.

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

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());
根据:


如果您特别想要这两个
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

虽然
期间
保留所有字段(8小时30分钟),但
小时
只关心小时,而丢弃其他字段。

非常有用,您实际上也回答了我昨天遇到的一个小问题。非常感谢分享您的专业知识!
// 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