Java如何找到两个LocalDateTime对象之间的差异?
在上一篇文章中,如何找到两次之间的差异?,我们LocalTime以秒为单位获得了两个对象之间的差异。在此示例中,我们将获得两个LocalDateTime对象之间的差异,并以年,月,日,小时,分钟,秒和毫秒为单位获取这些对象之间的差异。
package org.nhooo.example.datetime;import java.time.LocalDateTime;
import java.time.Month;
import java.time.temporal.ChronoUnit;
public class LocalDateTimeDiff {
public static void main(String[] args) {
LocalDateTime from = LocalDateTime.of(2015, Month.JANUARY, 10, 10, 0, 30);
LocalDateTime to = LocalDateTime.now();
LocalDateTime fromTemp = LocalDateTime.from(from);
long years = fromTemp.until(to, ChronoUnit.YEARS);
fromTemp = fromTemp.plusYears(years);
long months = fromTemp.until(to, ChronoUnit.MONTHS);
fromTemp = fromTemp.plusMonths(months);
long days = fromTemp.until(to, ChronoUnit.DAYS);
fromTemp = fromTemp.plusDays(days);
long hours = fromTemp.until(to, ChronoUnit.HOURS);
fromTemp = fromTemp.plusHours(hours);
long minutes = fromTemp.until(to, ChronoUnit.MINUTES);
fromTemp = fromTemp.plusMinutes(minutes);
long seconds = fromTemp.until(to, ChronoUnit.SECONDS);
fromTemp = fromTemp.plusSeconds(seconds);
long millis = fromTemp.until(to, ChronoUnit.MILLIS);
System.out.println("From = " + from);
System.out.println("To = " + to);
System.out.printf("The difference is %s years, %s months, %s days, " +
"%s hours, %s minutes, %s seconds, %s millis",
years, months, days, hours, minutes, seconds, millis);
}
}
上面的代码片段在执行时的结果是:
From = 2015-01-10T10:00:30To = 2016-02-11T17:20:40.503
The difference is 1 years, 1 months, 1 days, 7 hours, 20 minutes, 10 seconds, 503 millis
以上是 Java如何找到两个LocalDateTime对象之间的差异? 的全部内容, 来源链接: utcz.com/z/348725.html