对于年、月、日的差异,有一个java.time.Period,你可以很容易地得到你想要的:
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.of(2022, 1 , 25 , 12 , 20 , 33);
LocalDateTime now = LocalDateTime.now();
// get the difference in years, months and days
Period p = Period.between(now.toLocalDate(), localDateTime.toLocalDate());
// and print the result(s)
System.out.println("Difference between " + localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
+ " and " + now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + " is:\n"
+ p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days");
}
此代码示例的输出将是(当然取决于当天):
Difference between 2022-01-25T12:20:33 and 2020-02-25T10:52:43.327 is:
1 years, 11 months, 0 days
您可以使用java.time.Duration,如其他答案之一所示,以获得小时、分钟和秒的额外差异。看这个例子(基本上是上面加时间的计算):
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.of(2022, 1 , 25 , 12 , 20 , 33);
LocalDateTime now = LocalDateTime.now();
// get the difference in years, months and days (date related difference)
Period p = Period.between(now.toLocalDate(), localDateTime.toLocalDate());
// and the difference in hours, minutes and seconds (time-of-day related difference)
Duration d = Duration.between(now.toLocalTime(), localDateTime.toLocalTime());
long totalSeconds = d.getSeconds();
long hours = totalSeconds / 3600;
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
// and print the result(s)
System.out.println("Difference between " + localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
+ " and " + now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + " is:\n"
+ p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days, "
+ hours + " hours, " + minutes + " minutes, " + seconds + " seconds");
}
输出:
Difference between 2022-01-25T12:20:33 and 2020-02-25T11:25:42.712 is:
1 years, 11 months, 0 days, 0 hours, 54 minutes, 50 seconds
如果您正在接收java.util.Dates 或扩展遗留代码(或者如果您懒得将所有代码更改为使用java.time),您可以使用以下兼容方法:
LocalDateTime fromDate = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault());
Date fromLocalDateTime = Date.from(LocalDateTime.now().toInstant((ZoneOffset.UTC)));