Java jsr310:日期和时间之间的差异 [英] Java jsr310: difference between dates and times

查看:129
本文介绍了Java jsr310:日期和时间之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多SO问题涉及计算Java中两个日期或两次之间的差异。许多答案指出了核心Java Date类的问题,并建议使用Jodatime,但是AFAIK没有任何建议如何使用jsr310。

There are a plethora of SO questions that deal with calculating the difference between two dates or two times in Java. Many answers point out the problems with the core Java Date classes, and suggest using Jodatime, but AFAIK, there are none that suggest how to do this using jsr310.

所以,有没有办法在jsr310中计算两个日期或两次之间的差异?

So, are there any methods to calculate the difference between two dates or two times in jsr310?

为了参考,以下问题处理这个问题:

For reference, the following questions handle this issue:

在核心Java中:

  • milliseconds between two datetimes

在Jodatime中:

In Jodatime:

  • days betweens two dates
  • Interval between two datetimes

推荐答案

如何执行此操作取决于正在使用的日期或日期时间类。

How to do this depends on what date or datetime classes are being used.

使用时区等,所以datetime可以精确定位到时间线上的确切 Instant ),您可以使用持续时间 class( javadoc ) - 例如

If you are operating in real time (i.e. with time zones etc. so the datetime can be pinpointed to an exact Instant on the time-line), you can use the Duration class (javadoc) - e.g.

Duration diff = Duration.between(InstantProvider startInc, InstantProvider endInc);

其中InstantProvider可以

where an InstantProvider is able

如果您在假设时间(即没有时区等)运行,则可以使用期间类( javadoc )来获取两个实例之间的区别: LocalDate

Alternatively, if you are operating in hypothetical time (i.e. without time zones etc.), you can use the Period class (javadoc) to get the difference between two instances of LocalDate - e.g.

// diff in days, months and years:
Period diff = Period.between(LocalDate start, LocalDate end);

// diff in days:
Period diff = Period.daysBetween(LocalDate start, LocalDate end);

但是,我不知道有什么方便的方法来获取两个LocalDateTimes或LocalTimes之间的区别。但是...这可以使用Period来完成如下:

However, I'm not aware of any convenient methods for getting the difference between two LocalDateTimes or LocalTimes. But... this could be done using Period as follows:

// diff between LocalDateTimes:
public static Period between(LocalDateTime start, LocalDateTime end){
  return Period.of(
    end.getYear()-start.getYear(), 
    end.getMonthOfYear().getValue()-start.getMonthOfYear().getValue(), 
    end.getDayOfMonth()-start.getDayOfMonth(),
    end.getHourOfDay()-start.getHourOfDay(),
    end.getMinuteOfHour()-start.getMinuteOfHour(),
    end.getSecondOfMinute()-start.getSecondOfMinute(),
    end.getNanoOfSecond()-start.getNanoOfSecond()
  );
}

// diff between LocalTimes:
public static Period between(LocalTime start, LocalTime end){
  return Period.of(0, 0, 0,
    end.getHourOfDay()-start.getHourOfDay(),
    end.getMinuteOfHour()-start.getMinuteOfHour(),
    end.getSecondOfMinute()-start.getSecondOfMinute(),
    end.getNanoOfSecond()-start.getNanoOfSecond()
  );
}

这篇关于Java jsr310:日期和时间之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆