Java8:两个LocalDateTime在多个单位中的差异

我试图计算两个LocalDateTime之间的差异

输出的格式必须为y年m月d天h小时m分s秒。以下是我写的:

导入java.time.Duration;
导入java.time.Instant;
导入java.time.LocalDateTime;
导入java.time.Period;
导入java.time.ZoneId;
公共班机{
静态最终整数分钟/小时=60;
静态最终整数秒每分钟=60;
静态最终整数秒/小时=秒/分钟*分钟/小时;
公共静态void main(字符串[]args){
LocalDateTime toDateTime=LocalDateTime.of(2014,9,9,19,46,45);
LocalDateTime fromDateTime=LocalDateTime.of(1984,12,16,7,45,55);
期间=getPeriod(fromDateTime,toDateTime);
长时间[]=getTime(fromDateTime,toDateTime);
System.out.println(period.getYears()+“years”+
period.getMonths()+“months”+
period.getDays()+“天”+
时间[0]+“小时”+
时间[1]+“分钟”+
时间[2]+“秒”);
}
私有静态周期getPeriod(LocalDateTime dob,LocalDateTime now){
返回期.between(dob.toLocalDate(),now.toLocalDate());
}
private static long[]getTime(LocalDateTime dob,LocalDateTime now){
LocalDateTime today=LocalDateTime.of(now.getYear(),
now.getMonthValue()、now.getDayOfMonth()、dob.getHour()、dob.getMinute()、dob.getSecond());
Duration Duration=Duration.between(今天,现在);
long seconds=duration.getSeconds();
长时间=秒/秒/小时;
长分钟=((秒%秒/小时)/秒/分钟);
长秒=(秒百分比每分钟秒);
返回新的长[]{小时,分钟,秒};
}
}

我得到的结果是29年8个月24天12小时0分50秒。我已检查了此网站(带有值12/16/1984 07:45:5509/09/2014 19:46:45)。以下屏幕截图显示了输出:

我很确定我的代码中月值之后的字段是错误的。任何建议都会很有帮助

更新

我在另一个网站上测试了我的结果,结果不一样。这是:计算两个日期之间的持续时间(结果:29年8个月24天12小时0分50秒)

更新

由于我从两个不同的站点得到了两个不同的结果,我想知道我的计算算法是否合法。如果我使用以下两个LocalDateTime对象:

LocalDateTime-toDateTime=LocalDateTime.of(2014,9,10,6,40,45);
LocalDateTime fromDateTime=LocalDateTime.of(1984,12,16,7,45,55);

然后输出就来了:29年8个月25天-1小时-5分钟-10秒。

从这个链接应该是29年8个月24天22小时54分50秒。所以算法也需要处理负数

请注意,问题不在于哪个网站给了我什么结果,我需要知道正确的算法,需要有正确的结果。

我发现最好的方法是使用ChronoUnit。

long minutes=ChronoUnit.minutes.between(fromDate,toDate);
长时间=时间单位时间(从日期到日期);

其他文档位于此处:https://docs.oracle.com/javase/tutorial/datetime/iso/period.html

发表评论